MySQL GROUP_CONCAT中的条件

时间:2012-03-23 17:36:00

标签: mysql group-by group-concat

我有一个带有请求的MySQL表

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

以及对此类请求进行投票的表格。

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

我想要的观点:

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

然而,到目前为止,我只能做到这一点:

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

我使用的查询:

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;

所以我的问题是,如何在同一行中使用不同的值获得2个group_concats?

非常感谢!

2 个答案:

答案 0 :(得分:40)

试试这个:

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

结果:

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

答案 1 :(得分:1)

我尝试在另一个查询中重复使用您的查询

SELECT req_id,
   req_name,
   GROUP_CONCAT(case approved when 'YES' then voted_by else null end SEPARATOR ', ') AS approved_by,
   GROUP_CONCAT(case approved when 'NO' then voted_by else null end SEPARATOR ', ') AS rejected_by
FROM
(
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 voted_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
) t
group by req_id