我试图将逗号分隔的字符串与逗号分隔的MySQL字段相匹配。这应该再匹配一个逗号分隔的文本。
例子
字符串=apple, pineapple, grapes
MySQL字段=mango, oranges, apple
我尝试过MySQL IN
,但它只在字符串与MySQL文件完全匹配或字符串中只有一个项时工作
SELECT * FROM table1 WHERE field_1 IN (‘string’)
也试过没有任何运气。有人能告诉我怎么做到这一点吗?谢谢你的帮助。
最佳答案
为了实现上述结果以匹配记录,请执行以下脚本
创建临时表,将输入字符串作为行,分隔
drop temporary table if exists temp;
create temporary table temp( val varchar(255) COLLATE utf8_unicode_ci )
DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
set @sql = concat("insert into temp (val) values ('", replace(( select
group_concat(distinct ('mango,oranges,apple')) as data ), ",", "'),('"),"');");
prepare stmt1 from @sql;
execute stmt1;
将临时表与主表联接
select *
from
(
select distinct(val) as a from temp
)as splited
inner join
(
select 'apple, pineapple, grapes' as field
)as table1
where table1.field like concat('%',splited.a,'%');
关于mysql - 如何将逗号分隔的字符串与逗号分隔的MySQL字段匹配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51553879/