简体   繁体   English

从表中选择all甚至为null并加入

[英]Select all from table even null and join

I want to SELECT the all rows from meeting table even its null. 我想从会议表中选择所有行,即使它是null。 My table structure: 我的表结构:

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   

The output should be: 输出应该是:

If I SELECT the person_id 12 then it should return: 如果我选择person_id 12那么它应该返回:

date       |time
15-12-2014 | 02:02
17-12-2014 | 02:01
19-12-2014 | 02:03
21-12-2014 | NULL

If I SELECT the person_id 1 then it should return: 如果我选择person_id 1那么它应该返回:

date       |time
15-12-2014 | NULL
17-12-2014 | 02:20
19-12-2014 | NULL
21-12-2014 | NULL

It is a pretty straightforward outer join between the tables: 这是表之间非常简单的外连接:

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            

I have written a more detailed answer on these sorts of joins in the question and answer: How can an SQL query return data from multiple tables 我在问答中对这些类型的连接写了一个更详细的答案: SQL查询如何从多个表中返回数据

Edit: As per the comment by Andrew, the clause for the personID is in the join rather than in a normal where clause because it is an outer join. 编辑:根据Andrew的评论,personID的子句在连接中而不是在普通的where子句中,因为它是外连接。 If the condition was put into the where clause as normal, it would in fact negate the outer join completely. 如果条件正常地放入where子句中,它实际上会完全否定外连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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