[英]How to join tables including all ids from left table but only showing information from the right table given certain where clause
I have an attendees table with the following structure: 我有一个具有以下结构的与会者表:
+--------------+---------+
| attendee_id | others1 |
+--------------+---------+
| abcd | A |
| ghij | B |
| defg | C |
+--------------+---------+
And also an eventattendees table with the following structure: 还有一个具有以下结构的eventattendees表:
+--------------+---------+----------+
| attendee_id | others2 | event_id |
+--------------+---------+----------+
| wxyz | D | 1 |
| mlno | E | 2 |
| defg | F | 3 |
| defg | G | 2 |
| abcd | H | 1 |
+--------------+---------+----------+
What I want is to create a query that, given some event_id, returns a join of these tables (by attendee_id) that includes all attendee ids from attendee table and also returns the information from the eventattendde tables which a match for that event_id . 我想要的是创建一个查询,给定一些event_id,返回这些表的连接(通过attendee_id),其中包括来自与会者表的所有与会者ID,并返回eventattendde表中与该event_id匹配的信息。 Say, for event_id 3: 说,对于event_id 3:
+--------------+---------+---------+----------+
| attendee_id | others1 | others2 | event_id |
+--------------+---------+--------------------+
| abcd | A | null | null |
| ghij | B | null | null |
| defg | C | F | 3 |
+--------------+---------+--------------------+
How can I do that for mysql? 我怎么能为mysql做到这一点?
You need to put your where
criteria in the join
instead to respect the outer join
. 您需要将您的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
If you put it in the where
criteria, it will negate the outer join
. 如果将其放在where
条件中,它将取消outer join
。
Use left join 使用左连接
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;
你可以试试这个:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.