我想从会议表中选择所有行,即使它是空的。我的表格结构:
attandance table:
id | meeting_id | person_id | time
1 | 1 | 12 | 02:02
2 | 1 | 15 | 02:05
3 | 1 | 22 | 02:05
4 | 2 | 1 | 02:20
5 | 2 | 12 | 02:01
6 | 3 | 12 | 02:03
and meeting table:
id | date
1 | 15-12-2014
2 | 17-12-2014
3 | 19-12-2014
4 | 21-12-2014
输出应为:
如果我选择了个人识别码12,则它应返回:
date |time
15-12-2014 | 02:02
17-12-2014 | 02:01
19-12-2014 | 02:03
21-12-2014 | NULL
如果我选择了个人id 1,则它应返回:
date |time
15-12-2014 | NULL
17-12-2014 | 02:20
19-12-2014 | NULL
21-12-2014 | NULL
最佳答案
表之间的外部连接非常简单:
select
m.id,
m.date
a.time,
c.someColumn
from
meetings m
left outer join attendance a
on m.id=a.meeting_id
and a.person_id=:person
left outer join someTable c
on m.id=c.id
我写了一个更详细的答案,关于问答中的这些连接:How can an SQL query return data from multiple tables
编辑:根据Andrew的评论,personID的子句在join中,而不是在普通的where子句中,因为它是外部join。如果将条件作为普通条件放入where子句中,则实际上会完全否定外部连接。
关于php - 从表中全选,甚至为null并加入,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26556612/