我有一个具有以下结构的与会者表:
+--------------+---------+
| attendee_id | others1 |
+--------------+---------+
| abcd | A |
| ghij | B |
| defg | C |
+--------------+---------+
还有一个具有以下结构的eventattendees表:
+--------------+---------+----------+
| attendee_id | others2 | event_id |
+--------------+---------+----------+
| wxyz | D | 1 |
| mlno | E | 2 |
| defg | F | 3 |
| defg | G | 2 |
| abcd | H | 1 |
+--------------+---------+----------+
我想要的是创建一个查询,给定一些event_id,返回这些表的连接(by attendee_id),其中包括来自与会者表的所有与会者ID,并且还返回来自eventattendde的信息与 event_id 匹配的表格。比如说,对于event_id 3:
+--------------+---------+---------+----------+
| attendee_id | others1 | others2 | event_id |
+--------------+---------+--------------------+
| abcd | A | null | null |
| ghij | B | null | null |
| defg | C | F | 3 |
+--------------+---------+--------------------+
我怎么能为mysql做到这一点?
答案 0 :(得分:3)
您需要将where
条件放在join
而不是尊重outer join
。
select a.attendee_id, a.others1, e.others2, e.event_id
from attendees a
left join eventattendees e on a.attendee_id = e.attendee_id and e.event_id = 3
如果您将其置于where
条件中,则会取消outer join
。
答案 1 :(得分:0)
使用左连接
select a.attendee_id, a.others1, b.others2, b.event_id
from attendees as a
left join eventattendees on a.attendee_id = b.attendee_id and b.event_id= 3;
答案 2 :(得分:0)
你可以试试这个:
SELECT A.attendee_id, A.others1, ISNULL(B.others2,'empty') AS others2, ISNULL(B.event_id,'empty') AS event_id FROM TableA A LEFT JOIN TableB B ON A.attendee_id=B.attendee_id