![](/img/trans.png)
[英]Is a left outer join needed when I only need one column from the joined (right) table in the WHERE clause?
[英]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.