In MySQL how do I use a user defined variable in a WHERE IN clause?
-
26-10-2019 - |
Question
I don't understand why this does not work. Can someone explain what I need to do?
SET @my_list = '2,6,8,10,12,13,14,18,19,21';
DELETE FROM my_table WHERE my_table.table_id IN (@my_list);
Solution
It's interpreting @my_list as a single id and so you're asking it to delete from my_table where your id is the string "2,6,8,10,12,13,14,18,19,21"
You could try
SET @my_list = '2,6,8,10,12,13,14,18,19,21';
SET @exec = CONCAT('DELETE FROM my_table WHERE my_table.table_id IN (', @my_list ,')');
EXECUTE (@exec);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow