Mysql 查询逗号分隔字段值

标签 mysql

我有一个表,其中三个字段中的逗号分隔值包含三个不同表的主键,例如:

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/

相关文章:

php - 在 mysql 中选择早于当前日期的行

php - 选择员工姓名,他/她的 ID 将显示在 PHP 的文本框中

创建触发器时 MySQL 语法错误

mysql - 获取特定列中期望的所有 id

python - 无法打开包含文件 : 'mysql.h'

php - 在 phpmyadmin 中重新提交相同的 sql 文件

mysql - 比较 MySql 表

php - PHP 登录时向用户发送电子邮件通知

mysql - 使用多行作为一个订单

mysql - 使用 NodeJS 从 MySQL 数据库中检索数据并将其传递给 AngularJS 页面