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:
+--------------+---------+----------+
| 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 . Say, for 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?
You need to put your where
criteria in the join
instead to respect the 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
.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.