using mysql variable to hold comma separated value to be used for where in clause

大憨熊 提交于 2019-12-05 06:03:05

You need to have a dynamic sql on this,

SET @myIds = '1,2,3';
SET @sql = CONCAT('select something from sometable where someId in (',@myIds,')');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

The proper (and also more complicated) way to do that would be a temp table:

DROP TEMPORARY TABLE IF EXISTS `some_tmp_table`
CREATE TEMPORARY TABLE `some_tmp_table` (
    `id` INT(10) UNSIGNED NOT NULL
) ENGINE=MEMORY #memory engine is optional...

Insert your ID's the temp table

INSERT INTO some_tmp_table VALUES (1),(2),(3)...

and then use a JOIN instead of IN().

SELECT something 
FROM sometable s
JOIN some_tmp_table ts ON ts.id = s.someId

The other way is to use dynamic SQL as the other answer suggests. It might be simpler for you to generate the dynamic SQL in your app, but you can do it in MySQL too.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!