使用group_concat显示相关结果

时间:2014-12-27 23:34:10

标签: mysql

我试图获取与Feed X相对应的人的所有事件,并在单个查询中返回参加该事件的其他人。

 events (TABLE)
 - id int (10)
 - name varchar (20)

 events_people (TABLE)
 - id int (10)
 - event_id int (10)
 - person_id int (10)

 feed (TABLE)
 - id int (10)
 - feed_id varchar (20)
 - person_id int (10)

 people (TABLE)
 - id int (10)
 - first_name varchar (20)

我可以通过这个简单的查询得到这一点:

SELECT events.id AS event_id, GROUP_CONCAT(DISTINCT(people.first_name)) AS attending
FROM events
LEFT JOIN events_people ON events.id = events_people.event_id
LEFT JOIN people ON events_people.person_id = people.id
LEFT JOIN feed ON events_people.person_id = feed.person_id
GROUP BY events.id

但是一旦我添加了像WHERE feed.feed_id IN ('SHFDskdf')这样的条件,它就会过滤掉与Feed X无关的所有用户,从而打破群组连接。

我确定这不是火箭科学,但在花了几个小时之后我肯定会有这样的感觉。

SQL小提琴: http://sqlfiddle.com/#!2/3143c/2/0

1 个答案:

答案 0 :(得分:2)

只需将条件移至on子句:

SELECT events.id AS event_id, GROUP_CONCAT(DISTINCT(people.first_name)) AS attending
FROM events LEFT JOIN
     events_people
     ON events.id = events_people.event_id LEFT JOIN
     people
     ON events_people.person_id = people.id LEFT JOIN
     feed
     ON events_people.person_id = feed.person_id AND feed.feed_id IN ('SHFDskdf')
GROUP BY events.id;

编辑:

问题是过滤器对people.first_name没有影响。您可以使用case语句修复此问题:

SELECT e.id AS event_id,
       GROUP_CONCAT(DISTINCT case when f.person_id is not null then p.first_name end) AS attending
FROM events e LEFT JOIN
     events_people ep
     ON e.id = ep.event_id LEFT JOIN
     people p
     ON ep.person_id = p.id LEFT JOIN
     feed f
     ON ep.person_id = f.person_id AND f.feed_id IN ('SHFDskdf')
GROUP BY e.id;

这应该做你想要的。

编辑II:

现在我想我知道你想要什么:

SELECT e.id AS event_id,
       GROUP_CONCAT(DISTINCT p.first_name) AS attending
FROM events e LEFT JOIN
     events_people ep
     ON e.id = ep.event_id LEFT JOIN
     people p
     ON ep.person_id = p.id LEFT JOIN
     feed f
     ON ep.person_id = f.person_id 
GROUP BY e.id
HAVING SUM(f.feed_id IN ('SHFDskdf')) > 0;