SELECT
A.id AS id,
Group_Concat(B.value) AS values,
Group_Concat(C.ac_id) AS ac_id,
Concat(D.first_name,' ',D.last_name) AS updatedBy
FROM A
LEFT JOIN B
ON A.id = B.id
LEFT JOIN C
ON A.id = C.id
LEFT JOIN D
ON A.modified_by = D.user_id
WHERE
A.status!='deleted'
AND A.created_by = '18'
GROUP BY A.id;
表B& C有多个对应于A.id的行,这就是为什么我在这些字段上使用group_concat但是我得到的错误结果是那些分组的列.query返回结果如
+---------+-------------------------+-------------------------+-------------+
| id | values | ac_id | updatedBy |
+---------+-------------------------+-------------------------+-------------+
| 8 | A,A,A,B,B,B,C,C,C,D,D,D | 1,5,6,1,5,6,1,5,6,1,5,6 | Abdul |
+---------+-------------------------+-------------------------+-------------+
但我需要这样的输出
+---------+-------------------------+-------------------------+-------------+
| id | values | ac_id | updatedBy |
+---------+-------------------------+-------------------------+-------------+
| 8 | A,B,C,D | 1,5,6 | Abdul |
+---------+-------------------------+-------------------------+-------------+
答案 0 :(得分:3)
在DISTINCT
中使用GROUP_CONCAT()
。这样就不会显示重复项。
SELECT
A.id AS id,
Group_Concat(DISTINCT B.value) AS values,
Group_Concat(DISTINCT C.ac_id) AS ac_id,
Concat(D.first_name,' ',D.last_name) AS updatedBy
FROM A
LEFT JOIN B ON A.id = B.id
LEFT JOIN C ON A.id = C.id
LEFT JOIN D ON A.modified_by = D.user_id
WHERE A.status!='deleted' AND A.created_by = '18' GROUP BY A.id;
答案 1 :(得分:3)