繁体   English   中英

如何连接表,包括左表中的所有id,但只显示某些where子句的右表中的信息

[英]How to join tables including all ids from left table but only showing information from the right table given certain where clause

我有一个具有以下结构的与会者表:

+--------------+---------+
| 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,返回这些表的连接(通过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做到这一点?

您需要将您的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

使用左连接

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM