Conditions in MySQL GROUP_CONCAT

Rapsey picture Rapsey · Mar 23, 2012 · Viewed 17.3k times · Source

I have a MySQL table with requests

+--------+-------------+-----+
| req_id | req_name    | ... |
+--------+-------------+-----+
| 1      | testrequest | ... |
+--------+-------------+-----+

and a table with votes on such requests.

+--------+-----------+----------+
| req_id | vote_name | approved |
+--------+-----------+----------+
| 1      | User1     | 1        |
| 1      | User2     | 1        |
| 1      | User3     | 1        |
| 1      | User4     | 0        |
| 1      | User5     | 0        |
+--------+-----------+----------+

The kind of view I want:

+--------+-------------+---------------------+--------------+
| req_id | req_name    | approved_by         | rejected_by  |
+--------+-------------+---------------------+--------------+
| 1      | testrequest | User1, User2, User3 | User4, User5 |
+--------+-------------+---------------------+--------------+

So far, however, I've only been able to accomplish this:

+--------+-------------+----------+---------------------+
| req_id | req_name    | approved | by                  |
+--------+-------------+----------+---------------------+
| 1      | testrequest | YES      | User1, User2, User3 |
| 1      | testrequest | NO       | User4, User5        |
+--------+-------------+----------+---------------------+

The query I used:

SELECT requests.req_id, req_name, CASE
        WHEN approved THEN 'YES'
        ELSE 'NO'
        END AS approved, GROUP_CONCAT(vote_name ORDER BY vote_name ASC SEPARATOR ', ') AS by
FROM requests
LEFT JOIN votes ON requests.req_id = votes.req_id
GROUP BY requests.req_id, approved
ORDER BY requests.req_id DESC;

So my question is, how do I get 2 group_concats in the same row with different values?

Thanks a lot!

Answer

Mosty Mostacho picture Mosty Mostacho · Mar 23, 2012

Try this:

select r.req_id, r.req_name,
  group_concat(if(approved, vote_name, null) separator ', ') approvedBy,
  group_concat(if(approved, null, vote_name) separator ', ') rejectedBy
from requests r
left join votes v on r.req_id = v.req_id

Result:

+--------+-------------+---------------------+--------------+
| REQ_ID |  REQ_NAME   |     APPROVEDBY      |  REJECTEDBY  |
+--------+-------------+---------------------+--------------+
|      1 | testrequest | User1, User2, User3 | User4, User5 |
+--------+-------------+---------------------+--------------+