Mysql variable with multiple values

The following works as expected when a single value is stored in a variable:

Set @var = 121;
select * from table where id = @var;

How to set a variable with multiple values ​​and then use it in a query. I tried this, but it does not work:

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;
+4
source share
3 answers
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);

Thank you buddy

+3
source

To do this, you can set it @varas a comma-separated string and use both to obtain data. It's not perfect, but workable, and you need to take care of the value in @var. There should be no invalid char likespace

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.

+1

You must use IN

select * from table where id IN ( @var );
0
source

Source: https://habr.com/ru/post/1611740/


All Articles