查询返回错误结果

时间:2013-03-13 09:56:37

标签: mysql

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       |
+---------+-------------------------+-------------------------+-------------+

2 个答案:

答案 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)

这个问题已经解决了!

直接离开the documentation for GROUP_CONCAT

  

要消除重复值,请使用DISTINCT子句。

甚至还有一个方便的例子。

请使用文档。