2013-04-30 107 views
-3

我有兩個表,如下所示: -SQL查詢來連接兩個表

table1        table2 
date  time amount    date  time amount 
20120101 1000 101     20120104 1000 10 
20120101 1100 100     20120104 1100 11 
20120104 1000 101     20120105 1000 11 
20120104 1100 105     20120105 1100 8 

我想加入這兩個表得到的輸出如下:

date  time table1-amt table2-amt 
20120101 1000 101   NULL 
20120101 1100 100   NULL 
20120104 1000 101   10 
20120104 1100 105   11 
20120105 1000 NULL   11 
20120105 1100 NULL   8 

什麼是SQL查詢得到這個輸出?我正在使用mysql數據庫。

我嘗試以下查詢:

select table1.date,table1.time,table1.close , table2.close 
    from table1, 
     table2 
    where table1.date=table2.date 
    and table1.time=table2.time; 

它給了我輸出

date  time amount  amount 
    20120104 1000 101   10 
    20120104 1100 105   11 

人們正在指揮我對左外連接,全外連接我試過下面這做了兩個查詢nt解決我的目的。

​​
+0

什麼是您的預期輸出 – 2013-04-30 11:02:12

+3

您是否嘗試過任何操作?這是一個簡單的外連接。 – 2013-04-30 11:02:49

+0

[mysql left outer join]可能重複(http://stackoverflow.com/questions/3058834/mysql-left-outer-join) – APC 2013-04-30 11:09:35

回答

2

的做法,僅涉及到從每個表的讀數一次:

SELECT `date`, `time`, sum(`amt1`) as `table1-amt`, sum(`amt2`) as `table2-amt` 
FROM 
(SELECT `date`, `time`, amount as amt1, null as amt2 
FROM Table1 
UNION ALL 
SELECT `date`, `time`, null as am1, amount as amt2 
FROM Table2) v 
GROUP BY `date`, `time` 

(作爲反對在約迪的答案,每個從每個表讀取兩次鏈接的例子)

+0

我也想這樣做。但錯誤地做錯了。 +1 – hims056 2013-04-30 11:26:23

+0

@Mark Ba​​nnister謝謝。 – 2013-04-30 11:33:36

+0

@VirendraBisht:不客氣。 – 2013-04-30 11:34:24

1

這是你想要

Full Outer Join in MySQL

不會只給出了答案,你我在那裏找到和學到一些東西。

編輯:哦,有人毆打我,然後把它交給你^^。

+0

這些表之間沒有唯一的ID,這就是爲什麼我沒有從左外連接或全外連接獲得解決方案。謝謝 – 2013-04-30 11:32:56

+0

我試過以下兩個查詢,它們給了我想要的輸出結果,請你幫我弄清楚我想要的結果。 「select * from table1 left join table2 on table1.date = table2.date union select * from table1 right join table2 on table1.date = table2.date;」另一個是「select * from table1 left join table2 on table1.date = table2.date;」謝謝 – 2013-04-30 12:01:32

0

您需要一個FULL(外)JOIN。在MySQL中實現它的一種方法:

SELECT t1.date, t1.time, t1.close AS table1_amt, t2.close AS table2_amt 
FROM table1 AS t1 
    LEFT JOIN table2 AS t2 
    ON t1.date = t2.date 
    AND t1.time = t2.time 

UNION ALL 

SELECT t2.date, t2.time, t1.close, t2.close 
FROM table1 AS t1 
    RIGHT JOIN table2 AS t2 
    ON t1.date = t2.date 
    AND t1.time = t2.time 
WHERE t1.date IS NULL ;