I need to use an array of elements in query in jQuery. My query is:
"SELECT * FROM `projects` WHERE `Tags` LIKE CONCAT('%', ',', ('" + id + "'), ',', '%')"
Where id is an dynamic array, so I basically need:
"SELECT * FROM `projects` WHERE `Tags` LIKE CONCAT('%', ',', ('" + id[0] + "'), ',', '%') **OR LIKE id[1] OR LIKE id[2]**..."
if I'll use a forEach loop, it will return rows depending only on one of the elements in array, it is not support Like .. Or Like .. logic
var idArr = id.split(",");
idArr.forEach(function (id) {
_runQuery("SELECT * FROM `projects` WHERE `Tags` LIKE CONCAT('%', ',', '" + id + "', ',', '%')", function (rows) {....}
Given an array
var id = [1,2,3,4,5];
Try this
" WHERE tags LIKE '%"+ id.join("%' OR tags LIKE '%")+'%');
See it here: http://jsfiddle.net/XzXnf/
The simplest answer to your question is: Tags should probably be a separate table, then you would have:
"SELECT * from projects as p join tags as t on t.project_id = p.id where t.tag in (id[0], id[1], id[2]....)"
Of course, you can generate the required id string via a join easily enough (id.join(", ") will probably do it.
Alternatively, as #codingbiz points out, you can use a more complex id.join() call to expand the required OR's, but there are limits to that approach, and this is about as complex a query as you can reasonably make before normalising starts to look like a really good idea.
Related
Usually we will use SQL queries like below, we will pass params with predifined number $1
queryRunner.query('SELECT * FROM sample_data WHERE code IN ($1)', ['1'])
But I want to pass multiple params without predifined $1. Any way to resolve this?
queryRunner.query('SELECT * FROM sample_data WHERE code IN ($$)', ['1','2','3'])
One approach dynamically builds the IN clause based on the expected number of parameters. Consider:
var params = ['1','2','3'];
var inClause = '?' + ', ?'.repeat(params.length - 1);
var sql = 'SELECT * FROM sample_data WHERE code IN (' + inClause + ')';
console.log(sql);
Once we have a statement with the right number of placeholders, we can simply bind the collection or array with no trouble.
I am trying to basically ignore the case sensitivity for my db2 sql select * query, so that I can populate the products to my catalogue page. Ex. If I type in my search bar 'squeege', I want the item 'Squeege' to populate, even if there is a difference in Upper/lower case. What is the best way to do this, based on the code I have below?
var searchProduct = "select * from LISTOFPRODUCTS where ITEM LIKE '%" + searchValue + "%'"
Thanks in advance for the help :)
I think this could work:
var searchProduct = "select * from LISTOFPRODUCTS where UPPER(ITEM) LIKE UPPER('%" + searchValue + "%'")
Also the same with LOWER()
Note that the trick is parse both values to UPPER() or LOWER() to match them.
You can use the function LOWER().
For example:
var searchProduct = "select * from LISTOFPRODUCTS where LOWER(ITEM) LIKE '%" + searchValue + "%'"
You can also consider using REGEXP_LIKE which has a case-insensitive option i
Referring to the sample SQL statement below. I'm able to pass parameter values to the placeholder '?' in the statement. However I'm wondering whether it is possible to pass in the sort order in the same way?
So instead of this:
//Create SQL query
var getAccountsTransactionsStatement = WL.Server.createSQLStatement(
"SELECT transactionId, fromAccount, toAccount, transactionDate, transactionAmount, transactionType " +
"FROM accounttransactions " +
"WHERE accounttransactions.fromAccount = ? OR accounttransactions.toAccount = ? " +
"ORDER BY transactionDate DESC " +
"LIMIT 20;"
);
Can I have this:
//Create SQL query
var getAccountsTransactionsStatement = WL.Server.createSQLStatement(
"SELECT transactionId, fromAccount, toAccount, transactionDate, transactionAmount, transactionType " +
"FROM accounttransactions " +
"WHERE accounttransactions.fromAccount = ? OR accounttransactions.toAccount = ? " +
"ORDER BY ? DESC " +
"LIMIT 20;"
);
And to invoke it:
//Invoke prepared SQL query and return invocation result
function getAccountTransactions1(accountId){
return WL.Server.invokeSQLStatement({
preparedStatement : getAccountsTransactionsStatement,
parameters : [accountId, accountId, transactionDate]
});
}
Two things:
This query piece:
WHERE accounttransactions.fromAccount = ? OR accounttransactions.toAccount = ?
Could be replaced with this:
WHERE ? in (accounttransactions.fromAccount, accounttransactions.toAccount)
No you can't. Parameters are values - kind of static stuff - while column names are not. You could probably work around the issue somehow in limited way by using s.t. like this:
ORDER BY
CASE ?
WHEN 'transactionDate' THEN transactionDate
WHEN 'someotherdate' THEN someotherdate
ELSE DATE '2010-01-01'
END
Note however that's a messy construction. Also depending on the type of the database you're using you might want to cast all the columns into one data type i.e. string. so to_char(transactionDate,'yyyy-mm-dd hh24:mm:ss') might be in order but you need to ensure that the sorting is proper in your case (as number tend to mess stuff up like '2' > '13').
I have a query like this.
SELECT * FROM player_details where name in ('messi','neymar','suarez','alves')
I want to execute this query in titanium.
I tried like this
var in = ['messi','neymar','suarez','alves'];
db.execute('SELECT * FROM player_details where name in ?',in);
But above code producing error.
How can i add IN and NOT IN condition in sqlite in titanium ?
A single parameter ? replaces a single expression.
When you have four values, you need four parameters:
db.execute('SELECT * FROM player_details where name in (?,?,?,?)', in);
If the length of the array is dynamic try something like this:
var params = ["messi", "neymar", "suarez", "alves"],
qMarks = new Array(params.length).join("?,") + "?";
db.execute("SELECT * FROM player_details WHERE name in (" + qMarks + ");", params);
I want to create a dynamic function to INSERT data into the webSQL Database. I cannot use indexed DB because Zetakey does not support it.
tx.executeSql("INSERT INTO " + table + "(" + formatfields + ")
VALUES (" + formatqm + ")",
[formatvalues],
webdb.onSuccess,
webdb.onError);
Ich übergebe an den Query:
formatfields = "one, two"; (up to an undefined number)
formatqm = "?, ?";
formatvalues = "123, 456"; (dynamic user entries for x fields)
Can someone tell me what do I have to do with the formatvalues? When I write 123, 456 directly its working fine.
Thanks in advance!
Instead of dynamically create or change table column fields, use JSON serialization of the record. Basically store stringify user given object data on INSERT and parse on retrieval. If you need query over column, initialize those columns only. It will be just like IndexedDB does.
/*array.push */
formatvalues = new Array;
formatvalues.push("123");
and so on!