如何使用GROUP_CONCAT()获得所需的结果

时间:2019-04-16 05:20:14

标签: mysql

table 1: Operators
==============

operator_id |operator_name  |channel   |
------------+---------------+----------+
 1          |    operator1  |    1     |  
 2          |    operator2  |    2     |    
 3          |    operator3  |    0     |    
 4          |    operator4  |    3     |     
 5          |    operator5  |    0     |     
------------+---------------+----------+


table 2: Channels
==============

channel_id|operator_id |channel_name|
----------+------------+------------+
 1        |     2      |    Channel1|  
 2        |     1      |    Channel2|    
 3        |     2      |    Channel3|    
 4        |     3      |    Channel4|     
 5        |     5      |    Channel5|     
----------+------------+------------+


**Wanted result:**
==============

operator_name|channel_name      |    channel_id |
-------------+------------------+---------------+
 operator1   |Channel2          |       2       |  
 operator2   |Channel1,Channel3 |       1,3     |     
 operator3   |Channel4          |       4       |    
 operator4   |   0              |       0       |     
 operator5   |Channel5          |       5       |     
----------+---------------+---------------------+

我的查询:

SELECT A.*,O.*,
  GROUP_CONCAT(A.channel_name) AS channel_name,
  GROUP_CONCAT(A.channel_id) channel_id
FROM channels A
JOIN operators O
  ON O.operator_id = A.operator_id
GROUP BY operator_id

我想列出所有具有该通道的操作员,但是在我的查询中没有得到没有通道的操作员,如果在这种情况下没有操作员的通道,我还需要显示操作员列表*

1 个答案:

答案 0 :(得分:2)

使用左连接,并将NULL名称/ id级联替换为零作为占位符:

SELECT
    o.operator_name,
    COALESCE(GROUP_CONCAT(c.channel_name), '0') AS channel_name,
    COALESCE(GROUP_CONCAT(c.channel_id), '0') AS channel_id
FROM Operators o
LEFT JOIN Channels c
    ON o.operator_id = c.operator_id
GROUP BY
    o.operator_id,
    o.operator_name;   --  not necessary perhaps if operator_id is a PK

enter image description here

Demo