我有以下表格结构
Table 1 Table 2
---------- -------------------
Id value Id ids value
1 item1 1 1,3 Item1
2 item2 2 2,1 Item2
3 item3 3 1,3,5 Item3
4 item4 4 1 Item4
5 item5 5 2,1 Item5
现在我想从表2的值中获取与表1匹配的所有记录,例如表1中的ID与表2中的ID匹配
我想要这样的结果
table1.value table2.value
item1 Item1
item1 Item2
item1 Item3
item1 Item4
item1 Item5
item2 Item2
item2 Item5
item3 Item1
item3 Item3
item5 Item3
我已经使用以下查询
SELECT table1.value, table2.value FROM table1, table2 WHERE table1.id IN (table2.ids)
但是不能像我上面提到的那样被淘汰。有帮助吗?
最佳答案
这证明数据结构不良。您的数据应使用关联表而不是列表进行存储。但是您可以这样做:
select t1.value, t2.value
from table2 t2 join
table1 t1
on find_in_set(t1.id, t2.ids) > 0;
短语的另一种替代方法是使用
like
。尽管字符串连接有所不同,但这种想法适用于任何数据库:select t1.value, t2.value
from table2 t2 join
table1 t1
on concat(',', t2.ids, ',') like concat('%,', t1.id, ',%')
关于mysql - 在mysql中的两个表上获取记录匹配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17503113/