Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying MySQL using a set of values in a JavaScript array

Tags:

sql

node.js

mysql

I would like to submit a MySQL query that can be described something like "return all values from * if the id column matches any of the values in some array x."

Is there any way to use the entire contents of an array in a query in this way?

like image 479
erythraios Avatar asked May 07 '26 12:05

erythraios


1 Answers

var ids = [3, 4, 6, 8];
var query = 'SELECT * FROM table WHERE id IN (' + ids.join() + ')';

Now query contains query that will return all rows with id that matches any of the value in ids array.

With mysql package you can issue this query like this:

var mysql = require('mysql');

var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'admin',
  password : 'password'
});

// construct query
var ids = [3, 4, 6, 8];
var query = 'SELECT * FROM table WHERE id IN (' + ids.join() + ')';

connection.connect();

connection.query(query, function(err, rows, fields) {
  if (err) throw err;

  console.log(rows) // log all matching rows.
});
like image 124
rgtk Avatar answered May 10 '26 03:05

rgtk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!