在mysql中加入三个表

时间:2014-01-05 03:55:24

标签: mysql join

我有三张桌子

表1

 student_id |   id  |   status
--------------------------------

10  |   100 |   1
11  |   100 |   1
12  |   100 |   1
13  |   100 |   1
10  |   200 |   1
11  |   200 |   1
12  |   200 |   1
13  |   200 |   1

表2

date    |   status
------------------------    
2013-12-28  |   cd
2013-12-29  |   wd
2013-12-30  |   cd

表3

date    |   id
------------------------    
2013-12-28  |   100
2013-12-30  |   200

我需要2013-12-29所有学生的空值

示例:

sid |日期|状态|日期|状态     -------------------------------------------------- -----

10  |   2013-12-28  |   1     | 2013-12-28  |   cd
11  |   2013-12-28  |   1     | 2013-12-28  |   cd
12  |   2013-12-28  |   1     | 2013-12-28  |   cd
13  |   2013-12-28  |   1     | 2013-12-28  |   cd
10  |   null        |   null  | 2013-12-29  |   wd
11  |   null        |   null  | 2013-12-29  |   wd
12  |   null        |   null  | 2013-12-29  |   wd
13  |   null        |   null  | 2013-12-29  |   wd
10  |   2013-12-30  |   1     | 2013-12-30  |   cd
11  |   2013-12-30  |   1     | 2013-12-30  |   cd
12  |   2013-12-30  |   1     | 2013-12-30  |   cd
13  |   2013-12-30  |   1     | 2013-12-30  |   cd

我试过了 Join two tables in mysql?

我使用了以下查询

SELECT distinct x.student_id, table1.status, x.date bdate, table2.status bstatus 
FROM 
    (SELECT DISTINCT table1.student_id, table2.date 
     FROM table1 
          CROSS JOIN table2) x
          LEFT JOIN table1 ON x.sid=table1.sid 
          left join table3 on table1.id=table3.id and x.date=table3.date 
          LEFT JOIN table2 ON x.date=table2.date ORDER BY bdate, student_id

但我没有得到第三列状态的空值。

1 个答案:

答案 0 :(得分:1)

SELECT DISTINCT student_id,t3.date,IF(t3.date IS NULL, NULL,t1.status) as status,t2.date as date2,t2.status as status2
FROM table2 t2
LEFT JOIN table3 t3 USING(date)
JOIN table1 t1 ON (t1.id = t3.id OR t3.id IS NULL)
ORDER BY date2,student_id

sqlFiddle