问题:需要将一个字符串切割成数组作为in的查询条件,如:
select * from table_1 where name in (select slit(names) from table_2 where id =3);
names 返回的格式是’name1,name2,name3…',需要将name按照逗号切割作为in的查询条件;
mysql中没有split函数,这边有两种解决方案
方案1:使用mysql的高级函数FIND_IN_SET
试用场景:字符串不长,性能要求不高
select * from table_1 where FIND_IN_SET(name, select names from table_2 where id =3);
方案2:使用SUBSTRING_INDEX函数和自连接
使用场景:需要灵活的处理分割后的字符串,可处理较长的字符串
SELECT
*
FROM
table_1
WHERE
NAME IN (
SELECT
SUBSTRING_INDEX( SUBSTRING_INDEX( NAMES, ',', numbers.help_topic_id + 1 ), ',',- 1 )
FROM
( SELECT names FROM table_2 WHERE id = 14 ) AS t
JOIN mysql.help_topic AS numbers ON numbers.help_topic_id < LENGTH( NAMES )- LENGTH(
REPLACE ( NAMES, ',', '' ))+ 1
)
方案3:使用mysql的LOCATE函数
试用场景:性能和FIND_IN_SET函数基本一致
select * from table_1 where LOCATE(name, select names from table_2 where id =3);