MYSQL Join Left Condition不起作用

时间:2017-10-13 07:23:57

标签: mysql left-join

我有这个问题的例子: http://sqlfiddle.com/#!9/0cc41/1/0

描述: 有三个表(事件,人员和用户)。表人员连接事件和用户。 persons.type_id是events.id,persons.user_id是user.id.我创建了两个事件(id 1和2)。每个活动都有一个人参加。

我的Sql:

SELECT events.*, 
coalesce(part_person.Accept_Participants_LJ, 0) AS Accept_Participants
FROM events 
LEFT JOIN (
    SELECT GROUP_CONCAT(CONCAT(part_user.forname, ' ', part_user.surname) SEPARATOR ', ') AS Accept_Participants_LJ,
    part_person.type_id
    FROM persons AS part_person
    LEFT JOIN user AS part_user ON part_user.id = part_person.user_id 
    WHERE part_person.type = 'event_participant'
) part_person ON events.id = part_person.type_id
GROUP BY events.id 

我的期望是:

------------------------
|id|Accept_Participants|
------------------------
|1 | Carl Habicht      |
------------------------
|2 | Peter Zwegert     |
------------------------

如您所见,结果是:

----------------------------------
|id| Accept_Participants         | 
----------------------------------
|1 | Carl Habicht,  Peter Zwegert|
----------------------------------
|2 | 0                           |
----------------------------------

看来,他忽略了左连接的开启条件。

但是,我的错误在哪里?

1 个答案:

答案 0 :(得分:1)

Group_concat应该(几乎)总是有一个group by和group by而没有任何聚合是没用的 也许这就是你需要的

SELECT events.*, 
coalesce(part_person.Accept_Participants_LJ, 0) AS Accept_Participants
FROM events 
LEFT JOIN (
    SELECT GROUP_CONCAT(CONCAT(part_user.forname, ' ', part_user.surname) SEPARATOR ', ') AS Accept_Participants_LJ,
    part_person.type_id
    FROM persons AS part_person
    LEFT JOIN user AS part_user ON part_user.id = part_person.user_id 
    WHERE part_person.type = 'event_participant'
    group by part_person.type_id 
) part_person ON events.id = part_person.type_id
order  BY events.id