如何在mysql中将值与csv值进行比较?

时间:2012-03-30 06:58:25

标签: mysql

表1

id(int) |  name(varchar)
1       |  at,bat
2       |  cat,at,bat,mat
3       |  mat,cat
4       |  sat,bat

表2

id(int)  |  type(varchar)
1        |  at
2        |  mat

如您所见,table1包含csv字符串。现在,我需要从idTable 1来获取nameTable2存在于{{1}}类型字段中。

有没有任何纯mysql查询方式这样做?如果没有,在大型记录集的情况下,最有效的方法是什么?

2 个答案:

答案 0 :(得分:5)

我会使用FIND_IN_SET(str,strlist)

select distinct t1.id
from table1 t1
join table2 t2 on find_in_set(t2.type, t1.name) > 0

工作示例:http://sqlfiddle.com/#!2/b642c/4

答案 1 :(得分:2)

请参阅here

select a.ids as id1, b.ids as id2, a.name,b.type
from table1 a
inner join table2 b on find_in_set(b.type,a.name)