[英]Only GROUP_CONCAT active functions
我有四個表,一個clients , persons , client_functions和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
CF.archived = 0
轉換為SQL:
GROUP_CONCAT(IF(CF.archived = 0, F.description, NULL))
GROUP_CONCAT()
函數將忽略NULL
值。 但是,如果沒有可使用的非NULL
值,它將返回NULL
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.