2017-10-13 70 views
-1

我有我的問題的這個例子: http://sqlfiddle.com/#!9/0cc41/1/0MYSQL加入左條件不起作用

說明: 有三個表(事件,人物和用戶)。表人連接事件和用戶。 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       | 
---------------------------------- 

看來,他忽略了ON-左連接的條件。

但是,我的錯誤在哪裏?

回答

1

GROUP_CONCAT應該(幾乎)總是沒有任何的聚集是沒有用的有一組和組 這也許是你所需要的

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