mysql - 如果只有一个匹配,则返回连接表中的所有相关行
问题描述
可以说我有一张桌子叫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
解决方案
我认为您需要更改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 |
推荐阅读
- node.js - 我如何将新元素推送到子文档帖子>评论>回复>喜欢作为一个数组
- ruby-on-rails - Rails,没有控制器的帖子和页面的网址
- c++ - 使用对函数和 IO 对象(作为参数)的引用的目的是什么?
- xcode - bin/sh: /Users/xxx(bin/xcode_backend.sh: Not a directory Command PhaseScriptExecution failed with a nonzero exit code
- python - Twisted Server 通过 POST 接收数据流,延迟一个多小时逐字节读取 request.content.read()
- python - ValueError : x 和 y 的大小必须相同
- kurento - OpenVidu:有没有办法应用 textoverlay 过滤器,在每个订阅者屏幕上显示唯一值?
- java - 我想在每次位置更改时清除地图中的标记,而不是清除地图本身
- javascript - mapStateToProps 未运行
- ios - 马赛克灯光秀 CAReplicatorLayer 动画