我有以下表格。在MySQL中連接行
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 |
+-----+--------------+---------+
注意,對於命名AEB071
ID 155
是在LEFT JOIN
後重復。
我想結果如下(縮寫串聯)
+-----+--------------+--------------------+
| id | nomenclature | acronym |
+-----+--------------+--------------------+
| 155 | AEB071 | ALL, AML, AdCC |
| 156 | Nilotinib | NULL |
| 161 | Buparlisib | NULL |
| 162 | BYL719 | NULL |
+-----+--------------+--------------------+
我怎樣才能做到這一點使用MySQL查詢?
['GROUP_CONCAT()'](https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat )是獲得您正在尋找的結果的有效成分。 –
我的首選是在應用程序級代碼中處理這類事情。 – Strawberry