我有四个表,一个客户端,人员,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 |
---------------------------------------------
您的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;
GROUP_CONCAT()
中,我只想在CF.archived = 0
的情况下分组F.description
翻译成 SQL:
GROUP_CONCAT(IF(CF.archived = 0, F.description, NULL))
GROUP_CONCAT()
函数忽略NULL
值。但是,如果没有任何非NULL
值可供使用,它将返回NULL
。