San*_*ath 6 mysql variables where-clause in-clause
我必须运行这样的查询(查询1) -
select something from sometable where someId in (1,2,3)
Run Code Online (Sandbox Code Playgroud)
我想为ID部分保留一个变量,就像这样(查询2) -
set @myIds = "1,2,3";
select something from sometable where someId in (@myIds);
Run Code Online (Sandbox Code Playgroud)
但是这不会给出预期的结果(给出一个空的结果集),也没有查询错误.
我检查了如果我将逗号分隔的ID包装在引号内,查询结果为空结果集(查询3) -
select something from sometable where someId in ("1,2,3");
Run Code Online (Sandbox Code Playgroud)
I guess when I am using variable @myIds like I showed above (query 2), it is evaluating to the above query (query 3).
你需要有一个动态的sql,
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;
Run Code Online (Sandbox Code Playgroud)