在MySQL的`IN()`中使用逗号分隔的字符串 [英] Use a comma-separated string in an `IN ()` in MySQL
问题描述
如果用户定义的变量@x
是由逗号分隔的数字组成的字符串,例如'1,2,4'
,是否可以在IN ()
函数中使用它?
If a user-defined variable @x
is a string of comma separated numbers, e.g. '1,2,4'
, is there a way to use it in an IN ()
function?
特别是:
SET @x := '1,2,4';
SELECT * FROM t WHERE c IN (@x);
不选择t等于c等于1或2或4的行.
does not select rows in t where c equals 1 or 2 or 4.
推荐答案
您不能直接使用变量来执行此操作.根据您现在拥有的内容,服务器正在尝试执行select * form t where c in ('1,2,3');
...显然,鉴于要检查c是否包含给定的单个字符串,这显然不是您想要的.
You can't do this directly using a variable. Based on what you have now, the server is trying to execute select * form t where c in ('1,2,3');
... which clearly isn't what you want given that you're checking to see if c contains the single string given.
您必须根据列表生成动态SQL,以使其正常工作.
You must generate dynamic SQL based off of your list in order to get this to work.
这篇关于在MySQL的`IN()`中使用逗号分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!