简体   繁体   中英

Only GROUP_CONCAT active functions

I have four tables, a clients , persons , client_functions and functions table.

I wrote this query:

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

In my GROUP_CONCAT() i only want to group F.description if CF.archived = 0. Does anybody has an idea on how i can put a condition on the GROUP_CONCAT?

Current query results in:

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

But i only want to see the active functions

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

Your where is undoing some of your left join s. In fact, you don't need the clients table at all. Then you can put the filtering condition on functions in the ON clause:

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;

In my GROUP_CONCAT() i only want to group F.description if CF.archived = 0

Translated to SQL:

GROUP_CONCAT(IF(CF.archived = 0, F.description, NULL))

The GROUP_CONCAT() function ignores the NULL values. It returns, however, NULL if there isn't any not- NULL value to work with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM