首页 > 解决方案 > 如果只有一个匹配,则返回连接表中的所有相关行

问题描述

可以说我有一张桌子叫events

event_id | event_name | event_time
---------|------------|-----------
1        | Holiday    | 09:00
2        | Meeting    | 10:00

然后我有一张桌子叫attendees

attendee_id | event_id | person_id
------------|----------|----------
1           | 1        | 19
2           | 1        | 28
3           | 1        | 89
4           | 1        | 100
5           | 2        | 7
6           | 2        | 19
7           | 2        | 22
8           | 2        | 28

奇怪的是,如果我只匹配一个人,我需要返回活动及其所有参与者。如果没有匹配,我根本不希望事件返回。

SELECT events.*, GROUP_CONCAT(attendee_id, event_id, person_id SEPARATOR ',') AS attendees
FROM events
LEFT JOIN attendees ON events.event_id = attendees.event_id
WHERE attendees.person_id IN (89)
GROUP BY event_id

目前,这将返回“参加者”列中只有单个参加者的活动。

我知道这似乎违反直觉,但有没有一种方法可以让我真正返回活动以及活动中包含的所有参与者,而无需进一步过滤下游?

预期结果

event_id | event_name | event_time | attendees
-------- | ---------- | ---------- | ---------
1        | Holiday    | 09:00      | 19,28,89,100

标签: mysqlmariadb

解决方案


我认为您需要更改WHERE条款:

WHERE attendees.event_id IN (SELECT event_id FROM attendees WHERE person_id = 19)

所以使用这个:

SELECT 
  e.event_id, 
  GROUP_CONCAT(a.person_id SEPARATOR ',') AS attendees
FROM events e LEFT JOIN attendees a
ON e.event_id = a.event_id
WHERE a.event_id IN (SELECT event_id FROM attendees WHERE person_id = 19)
GROUP BY e.event_id

请参阅演示
结果:

| event_id | attendees    |
| -------- | ------------ |
| 1        | 28,89,100,19 |
| 2        | 7,19,22,28   |

推荐阅读