2014-01-05 68 views
-1

三個表我有三個表加入在MySQL

表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

​​

表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 

,但我did'nt得到第三列狀態空值。

+0

那麼,什麼是你的問題? – zerkms

+0

我查詢我沒有得到空值SELECT DISTINCT x.student_id,table1.status, x.date bdate,table2.status BSTATUS FROM(SELECT DISTINCT table1.student_id,table2.date FROM表1 CROSS JOIN表2)× LEFT JOIN表1 ON x.sid = table1.sid 左連接表3 上table1.id = table3.id 和x.date = table3.date LEFT JOIN表2 ON x.date = table2.date ORDER BY bdate,student_id – Madusudhanan

+0

如何在評論中添加以幫助任何人?將其添加到您的問題。 – Daedalus

回答

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

+0

它的工作。請詳細說明這個查詢如何工作 – Madusudhanan

+0

以及首先你想保留table2中的所有日期,所以你留下來加入它與table3,以獲得3行,一個爲t3爲空值。然後你加入table1,其中id或t3.id爲空,所以你會得到多個匹配的id和多個空行,但是Distinct會去掉第二組空行。你可以嘗試沒有獨特的看到。 –