我想这样做
set @a =(1,2,3);
select * from mytable where somefield in @a;
但是mysql不喜欢它。
我该怎么做?
答案 0 :(得分:1)
解决这个问题的一种方法
SET @a = '1,2,3';
SELECT *
FROM mytable
WHERE FIND_IN_SET(somefield, @a) > 0;
注意:这样可以有效地进行全面扫描。
恕我直言,你最好没有包含字符串的用户变量
SELECT *
FROM mytable t JOIN
(
SELECT 1 somefield UNION ALL
SELECT 2 UNION ALL
SELECT 3
) q
ON t.somefield = q.somefield;
另一个选择是利用动态SQL
SET @a = '1,2,3';
SET @sql = CONCAT('SELECT * FROM mytable WHERE somefield IN(', @a, ')');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
以下是所有查询的 SQLFiddle 演示
答案 1 :(得分:0)
您可以使用临时表执行此操作,如以下问题: How can I simulate an array variable in MySQL?
或者您可以在此问题中使用find_in_set(): how to set an array as a mysql user variable
答案 2 :(得分:0)
试试这个
SET @a = '1,2,3';
SET @sql = CONCAT('SELECT * FROM test WHERE `user` IN(', @a, ')');
PREPARE stmt FROM @sql;
EXECUTE stmt;
答案 3 :(得分:0)
可以通过适当的语法和准备声明来完成,但是:
set @a =1,2,3;
select * from mytable where somefield in (@a);
set @crt=concat("select * from mytable where somefield in ",concat('(',@a,')'),";");
prepare smnt from @crt;
EXECUTE smnt;
DEALLOCATE PREPARE smnt;