我有四个表,一个客户,人, client_functions 和功能表。
我写了这个查询:
SELECT
P.number,
P.first_name
GROUP_CONCAT(F.description) AS Functions
FROM clients AS C
LEFT JOIN persons AS P ON P.id=C.id
LEFT JOIN client_functions as CF ON CF.client_id=C.id
LEFT JOIN functions AS F ON F.id=CF.function_id
WHERE P.person_type = 'client' AND P.company_id = 3
GROUP BY
P.number,
P.first_name
在我的GROUP_CONCAT()中,如果CF.archived = 0,我只想对F.description进行分组。是否有人知道如何在GROUP_CONCAT上设置条件?
当前查询结果为:
--------------------------------------------
| 93 | Jan Lochtenberg | PV,PV,PV,PV |
| 94 | Chris van Eijk | VP-I,VP,PV |
| 95 | Gertrude Irene | VP-I,PV,PV,PV |
| 96 | Wiekert Jager | VP-I,PV |
| 97 | Antonius Kode | VP,VP-I,VP |
| 98 | HansLelie | PV,PV,PV |
---------------------------------------------
但我只想看到活跃的功能
--------------------------------------------
| 93 | Jan Lochtenberg | PV |
| 94 | Chris van Eijk | VP-I,VP,PV |
| 95 | Gertrude Irene | VP-I,PV |
| 96 | Wiekert Jager | VP-I,PV |
| 97 | Antonius Kode | VP,VP-I,VP |
| 98 | HansLelie | PV |
---------------------------------------------
答案 0 :(得分:1)
您的where
正在取消部分left join
。事实上,您根本不需要clients
表。然后,您可以将过滤条件放在ON
子句中的函数中:
SELECT P.number, P.first_name, P.last_name,
GROUP_CONCAT(F.description) AS Functions
FROM persons P LEFT JOIN
client_functions CF
ON CF.client_id = p.id LEFT JOIN
functions F
ON F.id = CF.function_id AND cf.archived = 0
WHERE P.person_type = 'client' AND P.company_id = 3
GROUP BY P.number, P.first_name, P.last_name;
答案 1 :(得分:0)
在我的
,我只想将GROUP_CONCAT()
中,如果F.description
CF.archived = 0
分组
转换为SQL:
GROUP_CONCAT(IF(CF.archived = 0, F.description, NULL))
GROUP_CONCAT()
函数忽略NULL
值。但是,如果没有任何非NULL
值可用,则会返回NULL
。