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
insert into t_city values (1,'北京'),(2,'上海'),(3,'广州'),(4,'深圳'),(5,'杭州'),(12,'武汉');
- 1
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
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
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
Summary:
This usage is very limited, and it will only be used in some special cases. Record it here.