Question

I now gave up and sorted it by other means but because "curiosity killed the cat" I am trying to figure out how to use mysql query @variables within an IN where statement:

So, from this:

SELECT * FROM table1 WHERE table1.ID IN (794,758)

Try to include a variable and this returns a syntax error:

SET @variousids="(794,758)";
SELECT * FROM table1 WHERE table1.ID IN @variousids

This returns values only from the first:

SET @variousids="794,758";
SELECT * FROM table1 WHERE table1.ID IN (@variousids)

I've tried different syntax, values and have not found any specific doc about defining list of values.

Was it helpful?

Solution

Try :-

SET @variousids="794,758";
SELECT * FROM table1 WHERE table1.ID FIND_IN_SET (table1.ID,@variousids)

OTHER TIPS

Use find_in_set . The below will work.

SET @variousids="794,758";
SELECT * FROM table1 WHERE find_in_set(table1.ID,@variousids)

Use dynamic SQL:

SET @variousids="794,758";
prepare stmt from 'SELECT * FROM table1 WHERE table1.ID IN ( ? )'
execute stmt using @variousids;

For more info, check THIS article.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top