Php 从表中选择all(即使为null)并连接
我想从会议表中选择所有行,即使它为空。我的表格结构:Php 从表中选择all(即使为null)并连接,php,mysql,sql,Php,Mysql,Sql,我想从会议表中选择所有行,即使它为空。我的表格结构: 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
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
输出应为:
如果我选择person_id 12,则它应返回:
date |time
15-12-2014 | 02:02
17-12-2014 | 02:01
19-12-2014 | 02:03
21-12-2014 | NULL
date |time
15-12-2014 | NULL
17-12-2014 | 02:20
19-12-2014 | NULL
21-12-2014 | NULL
如果我选择person_id 1,则它应返回:
date |time
15-12-2014 | 02:02
17-12-2014 | 02:01
19-12-2014 | 02:03
21-12-2014 | NULL
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
我在问答中就这些连接写了更详细的回答:
编辑:根据Andrew的评论,personID的子句位于联接中,而不是普通的where子句中,因为它是外部联接。如果将该条件作为正常条件放入where子句中,它实际上会完全否定外部联接。Spot on。您可能需要解释为什么在join子句中需要对person_id进行约束。您从哪里获得缩进样式的?谢谢Fluffe,此代码正在运行,但在我的代码中,我有另外两个join表,这使我无法获得我想要的结果。我将outer join 2留在了其他表中,但仍然不会。@SuSu只要条件在联接中,而不是where子句中,您就应该能够从查询中获得所需的内容。根据安德鲁的评论,我又加了一点解释。@AirThomas有什么问题吗?我总是这样写我的查询,所以它很好而且容易阅读:)您可以学习如何执行外部联接。