我有以下表格。
CREATE TABLE `cms_compound` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`nomenclature` varchar(50) DEFAULT NULL,
`version_number` bigint(20) DEFAULT NULL,
`version_region_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `cms_compound_disease` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`compound_id` bigint(20) NOT NULL,
`disease_id` bigint(20) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `cms_disease` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`title` varchar(50) DEFAULT NULL,
`acronym` varchar(50) DEFAULT NULL,
`version_number` bigint(20) DEFAULT NULL,
`version_region_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `cms_version_region` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`version_id` bigint(20) NOT NULL,
`region_id` bigint(20) NOT NULL,
PRIMARY KEY (`id`)
);
我正在使用以下查询
SELECT SQL_CALC_FOUND_ROWS
c.id,
c.nomenclature,
d.acronym
FROM
compound c
LEFT JOIN
compound_disease cd ON (cd.compound_id = c.id)
LEFT JOIN
disease d ON (cd.disease_id = d.id)
LEFT JOIN
version_region vr ON (vr.id = c.version_region_id)
WHERE
c.version_number = 2 AND vr.version_id = 2 AND vr.region_id = 1
LIMIT 0, 10
这给了我以下结果。
+-----+--------------+---------+
| id | nomenclature | acronym |
+-----+--------------+---------+
| 155 | AEB071 | ALL |
| 155 | AEB071 | AML |
| 155 | AEB071 | AdCC |
| 156 | Nilotinib | NULL |
| 161 | Buparlisib | NULL |
| 162 | BYL719 | NULL |
+-----+--------------+---------+
请注意,155
之后会重复命名AEB071
的ID LEFT JOIN
。
我想要以下结果(首字母缩略词连接)
+-----+--------------+--------------------+
| id | nomenclature | acronym |
+-----+--------------+--------------------+
| 155 | AEB071 | ALL, AML, AdCC |
| 156 | Nilotinib | NULL |
| 161 | Buparlisib | NULL |
| 162 | BYL719 | NULL |
+-----+--------------+--------------------+
如何使用MySQL查询执行此操作?
答案 0 :(得分:2)
SELECT SQL_CALC_FOUND_ROWS
c.id,
c.nomenclature,
GROUP_CONCAT(d.acronym)
FROM
compound c
LEFT JOIN
compound_disease cd ON (cd.compound_id = c.id)
LEFT JOIN
disease d ON (cd.disease_id = d.id)
LEFT JOIN
version_region vr ON (vr.id = c.version_region_id)
WHERE
c.version_number = 2 AND vr.version_id = 2 AND vr.region_id = 1
GROUP BY
c.id,
c.nomenclature