当变量中存储单个值时,以下工作正常:
Set @var = 121;
select * from table where id = @var;
如何设置具有多个值的变量,然后在查询中使用它。我试过这个,但它不起作用:
set @var = (
117,120,121,122,143,151,175,233,387,189,118,119,339,357,500,501,493,425,307,191,
117,120,121,122,143,151,175,233,387,189,118,119,339,357,500,501,493,425,307,191,
117,120,121,122,143,151,175,233,387,189,118,119,339,357,500,501,493,425,307,191
)
select * from table where id = @var;
答案 0 :(得分:3)
set @var = '
117,120,121,122,143,151,175,233,387,189,118,119,339,357,500,501,493,425,307,191,
117,120,121,122,143,151,175,233,387,189,118,119,339,357,500,501,493,425,307,191,
117,120,121,122,143,151,175,233,387,189,118,119,339,357,500,501,493,425,307,191'
SELECT * FROM table WHERE FIND_IN_SET(id,@var);
感谢好友
答案 1 :(得分:1)
您可以通过将@var
设置为逗号分隔字符串并使用like来获取数据。这不完美但可行,你必须关注@var
中的价值。不应该有space
Mysql> set @var = '117,120,121,122,143,151,175,233,387,189,118,119,339,357,500,501,493,425,307,191,117,120,121,122,143,151,175,233,12';
Query OK, 0 rows affected (0.00 sec)
Hitesh> select * from test where ((@var like concat(id,',%')) or (@var like concat('%,',id)) or (@var like concat('%,',id,',%')) or (@var like id));
+----+------+-------+
| ID | NAME | VALUE |
+----+------+-------+
| 12 | Nee | NULL |
+----+------+-------+
1 row in set (0.00 sec)
您也可以使用LOCATE
功能代替like
。 MySQL LOCATE()返回字符串中第一次出现字符串的位置。这两个字符串都作为参数传递。可选参数可用于指定将从哪个位置开始搜索(即,要搜索的字符串)搜索。如果未提及此位置,则从头开始搜索。
语法LOCATE(substr,str)
mysql> SELECT LOCATE('st','myteststring');
+-----------------------------+
| LOCATE('st','myteststring') |
+-----------------------------+
| 5 |
+-----------------------------+
FIND_IN_SET()
非常适合您的情况。它must have strin
g的值为comma separated
。
答案 2 :(得分:0)
你应该使用IN
#