3

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?

3
  • Because @var1 is a varchar variable and not a list of values. Commented Jun 17, 2019 at 13:34
  • 1
    Not that it matters but you are testing @VAR which you haven't set up. Commented Jun 17, 2019 at 13:36
  • Have you checked for obvious typos? Commented Jun 17, 2019 at 13:50

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.