我有一个表,其中三个字段中的逗号分隔值包含三个不同表的主键,例如:
Table A (Main table):
id title companyid countryid regulatorid
1 tit1 1,2 2,3 2,1
2 tit2 3,1 1,2 1,3
Table B (company) table c (Country) table d(regulator)
id title id title id title
1 comp1 1 country1 1 regul1
2 comp2 2 country2 2 regulator2
3 comp3 3 country3 3 regulator
我想要得到如下结果:
id title company country regulator
1 tit1 comp1,comp2 country2,counrtry3 regulator2,regul1
2 tit2 comp3,comp1 country1,country2 regul1,regulator3
我做了这样的查询:
select id,title,group_concat(table B.title) AS company,group_concat(table c.title) AS
country,group_concat(table d.title) AS regulator from table A INNER JOIN table b on
find_in_set(table B.id,table A.companyid) > 0 INNER JOIN table c on find_in_set(table
c.id,table A.countryid) > 0 INNER JOIN table d on find_in_set(table d.id,table
A.regulatorid) > 0
我必须更改什么才能获得当前结果?
最佳答案
这是一种非常糟糕的数据格式,在回答之前,我应该让你 promise 如果你能控制它就改变格式。这实际上应该是三个额外的单独的关联/连接表。如果您要使用关系数据库,请正确使用它。
select a.id, a.title, group_concat(distinct b.title), group_concat(distinct c.title),
group_concat(distinct d.title)
from a left outer join
b
on find_in_set(b.id, a.companyid) > 0 left outer join
c
on find_in_set(c.id, a.countryid) > 0 left outer join
d
on find_in_set(d.id, a.regulatorid) > 0
group by a.id, a.title;
但是改变表格布局会好很多。
关于Mysql 查询逗号分隔字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22735293/