MarcoTroise79
MarcoTroise79

Reputation: 37

Mysql select in variable

I need a query like this.

Set @var1:="30,31";
Select * from mytable where id in (@var)

I've tried on more tables, but MySQL returns null value. Why?

Upvotes: 3

Views: 94

Answers (2)

Alberto Moro
Alberto Moro

Reputation: 1013

You can do with find_in_set() check Here

SET @var1 = "30,31";
SELECT * FROM mytable WHERE find_in_set(myTable.myColumn, @var1);

MySQL return NULL value because search string and not a list of values

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521239

You need dynamic SQL to do this. Prepared statements are one general way to go, except that binding an unknown number of values to a WHERE IN clause is difficult. Assuming you always would be binding only two values, we can try:

SET @sql = 'SELECT * FROM mytable WHERE id IN (?, ?)';
PREPARE stmt2 FROM @sql;
SET @var1 = 30;
SET @var2 = 31;
EXECUTE stmt2 USING @var1, @var2;

Upvotes: 1

Related Questions