MySQL uses instr to achieve the effect of in (string)

When using mysql, I encounter a situation: 
I need to find out the record of the id in a string concatenated with an id. At this time, it id in(id1,id2,...)does not work, because the parameters in the in syntax are numeric, and the instr syntax should be used, instr(idsStr,id)where idsStr=' id1,id2,id3...' 
The following example illustrates:

1 Create a table

create table t_city (id int(10) ,name varchar(20));
  • 1

write picture description here

insert into t_city values (1,'北京'),(2,'上海'),(3,'广州'),(4,'深圳'),(5,'杭州'),(12,'武汉');
  • 1

write picture description here

2 query

Now I need to query the city whose id is in the string '1, 2, 3', but it is not possible to use the in syntax, because the parameter of the in syntax is not a string, the following method can be used to achieve the same effect

select * from t_city where instr('1,2,3',id);
  • 1

select * from t_city where instr(id,'1,2,3'); 
The result is correct. But if I want to query the cities whose id is in the string '3,4,5,12', I will find that the results are biased, and 6 cities are found

select * from t_city where instr('3,4,5,12',id);
  • 1

write picture description here 
It turns out that Wuhan's id is 12, Beijing's id is 1, and Shanghai's id is 2. According to the semantics of instr, id=1 or 2 or 12 can be found, so modify the search method.

select * from t_city where instr(concat(',','3,4,5,12',','),concat(',',id,','));
  • 1

write picture description here

Summary: 
This usage is very limited, and it will only be used in some special cases. Record it here.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324437294&siteId=291194637
Recommended