**## Node ##
Loopback Node**
Like select Fetch Multiple Category Id From Product Table.
Pass your category id in above Bold Parameter
let tempQuery += " `categoryId` IN " + **categoryId**;
var query = "SELECT * FROM `product` WHERE **tempQuery** ";
Above Code will give response Like...
It fetches all categories and gives in response now in temp query variable matches category id with the response and return products if matches any
If In SQL
consider 1,2,3,4,5 as Id
"select * from info WHERE `id` IN ('1,2,3,4,5')"
I find it really difficult to understand your question. Are you trying to write a LoopBack query to match multiple ids? If that's the case, then you can use the inq operator as described here.
const filter = {where: {id: {inq: [1,2,3,4,5]}}};
// LoopBack 3.x
const found = await Category.find(filter);
// LoopBack 4.x
const found = await categoryRepo.find(filter);
Related
Here is the query
SELECT * from tableA WHERE tableA.id NOT IN (SELECT tableB.a_id FROM tableB);
Same query how to write using TypeORM typescript?
Below is code, I tried which is not working
this.createQueryBuilder('tableA')
.where(`tableA.id != :id`, { id })
const tableBqry = tableBRepository
.createQueryBuilder('tableB')
.select("tableb_id");
const tableAqry = tableARepository
.createQueryBuilder('tableA')
.where("tableA.id NOT IN (" + tableBqry.getSql() + ")");
const results = await tableAqry.getMany();
This method will work fine for the above-mentioned problem.
You can select IDs from tableB first, and then use the IDs you've got (I assume that they are mapped and stored in var ids: string[]) to make a query for tableA.
this.createQueryBuilder('tableA')
.where(`tableA.id <> ALL(:ids)`, { ids })
I am trying to pass array of cities to the IN clause but seems inverted commas are removed while preparing query
Here is the code
let city = ["Moscow", "Paris"];
let sql = 'SELECT* FROM cities WHERE city IN ('+city+')';
console.log(sql);
and in the console I am getting this
SELECT* FROM cities WHERE city IN (Moscow, Paris);
and thus getting exception while executing query!
Any help?
Try this, it will work
var sql = "SELECT uid FROM cities where city IN ('" + gender.join("','") + "')";
Result :-
SELECT uid FROM cities where city IN ('Male','Female')
Using a Query Builder is a preferable method but a possible solution if you have a long array:
let stringifiedValues = JSON.stringify(city).replace(/\[|\]/g,'');
let sql = `SELECT * FROM cities WHERE city IN (${stringifiedValues})`;
Use the map function to transform all items in your array. You want to add quotes to the items like this Moscow => 'Moscow'
Use the join to gather the transformed items into a string. The delimiter can be specified as an argument like this array.join(', ')
Use template literals (string interpolation) to inject your string in your query. Like this ${str}
const city = ["Moscow", "Paris"];
const injectedString = city.map(c => `'${c}'`).join(', ');
let sql = `SELECT * FROM cities WHERE city IN (${injectedString})`;
console.log(sql);
I have this scenario that I can't figure out:
Inside table wp_comment I need to list all user_id (not duplicate) with comment_type=complete.
I tried this:
$results = $GLOBALS['wpdb']->get_results( "SELECT * FROM wp_comments WHERE comment_type='sensei_course_status' AND comment_approved='complete'", ARRAY_A );
$corsisti = $results[user_id];
// I need to print only ids to put this array in
get_users( include=> '$corsisti' )
The database screenshot:
You can use the wpdb::get_col() method to retrieve an array with values from a single column:
$corsisti = $GLOBALS['wpdb']->get_col( "SELECT `user_id` FROM wp_comments WHERE comment_type='sensei_course_status' AND comment_approved='complete'");
Then simply use the result in get_users (you do not need the quotes):
$users = get_users( include=> $corsisti );
I have 2 arrays :
columns = ['column1', 'column2'];
data = ['data1', 'data2'];
I'd like to update the table using a prepared query:
conn.query('UPDATE table SET ?? = ? WHERE id = ?', [columns, data, id],
function(err, info){
Excepted sql query :
UPDATE table SET column1 = 'data1', column2 = 'data2' WHERE id = 10
But I get something that looks like :
UPDATE table SET 'column1', 'column2' = 'data1', 'data2' WHERE id = 10
This feature works well for select or insert but it seems not working for update queries. Any thoughts on how I can get this work ?
From node-mysql docs, about escaping query values, we have this:
Arrays are turned into list, e.g. ['a', 'b'] turns into 'a', 'b'
, so it won't work the way you expect.
But, in the docs we also have this:
Objects are turned into key = 'val' pairs. Nested objects are cast to strings.
with an example:
var post = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
// Neat!
});
console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
So, in order to do what you want, the best option IMO, is to convert your arrays into an object like:
{
column1: 'data1',
column2: 'data2'
}
Just to clarify, since after Googling for ages I didn't find an exact example to show what I was looking for. Here is the code which hopefully is what Bobby Shark found out, since I don't think 'SET ??' works.
To UPDATE multiple columns (but not necessarily all) for one row, without typing up every column in the query, but passing an object of {column_name1: 'new_foo', column_name2: 'new_bar', column_name2: 'new_baz'}
(using body-parser to get object of form data)
var blog = req.body.blog; // object as described above
var sql = "UPDATE blog SET ? WHERE id = ?";
connection.query(sql, [blog, req.params.id], function(err, updatedBlog){
if(err){
console.log(err);
} else {
res.redirect("/blogs/" + req.params.id);
}
});
This post by Bala Clark helped (though we've read it in the docs 10 times!). Hope this helps to see example code of object with multiple column updates (name/value pairs). Again found no specific examples in many sites.
There are 30 tables(categories) all with the same structure storing news items with a siteID field to filter on a particular client.
The client select which tables(categories) they show by setting the field visible(tinyint) field to 1 or 0.
I have the following test MYSQL which works okay. I am using Applicationcraft.com so the syntax is different than standard MYSQL but you can see the query.
function _getAllData(cObj,p){
var result = [];
console.log('started');
selectObj=cObj.select().from('schoolNews').order('newsIDDESC').where('siteID=?',p.siteID);
result[0] = cObj.exec(selectObj);
selectObj=cObj.select().from('schoolDocs').order('newsIDASC').where('siteID=?',p.siteID);
result[1] = cObj.exec(selectObj);
return result;
}
So I have an array with the results of each table in result[0] & result[1].
So I created the following to :
function _getAllData(cObj,p){
var result = [];
console.log('started');
selectObj=cObj.select().from('schoolNews').order('newsIDDESC').where('siteID=?',p.siteID).where('visible=?',1);
result[0] = cObj.exec(selectObj);
selectObj=cObj.select().from('schoolDocs').order('newsIDASC').where('siteID=?',p.siteID).where('visible=?',1);
result[1] = cObj.exec(selectObj);
selectObj=Obj.select().from('schoolNews_copy').order('newsIDDESC').where('siteID=?',p.siteID).where('visible=?',1);
result[2] = cObj.exec(selectObj);
selectObj=cObj.select().from('schoolNews_copy').order('newsIDDESC').where('siteID=?',p.siteID).where('visible=?',1);
result[3] = cObj.exec(selectObj);
selectObj=cObj.select().from('schoolNews_copy').order('newsIDDESC').where('siteID=?',p.siteID;
result[4] = cObj.exec(selectObj).where('visible=?', 1);
upto result[30].
I have populated schoolNews_copy with 1000 records and run the query from my app.
I am getting a timed out error.
Is this because.
query the same table causes the problem.
This is the wrong approach all together.
If not what is the best approach.
Is there a way to query every table in a single statement and populate the results into an array named results.
So the result I need is an example array :
result[0] has data visible set to 1
result[1] has data visible set to 1
result[2] has data visible set to 0
I have now restructured the table as you said. And using joins can get all the info I need in one query.
SELECT * FROM categories INNER JOIN allNews on allNews.catID = categories.catID WHERE categories.visible = 1 AND categories.siteID = '+p.siteID;
MrWarby.