2013-07-06 80 views
1

我有兩個表如下:MYSQL UNION ALL與唯一的行

Table1 

id   date   pprice 
1   22-1-2013  54.56 
2   15-2-2013  55.64 
3   25-3-2013  57.62 

Table2 

id   date   dprice 
1   12-1-2013  66.56 
2   17-2-2013  68.59 
3   25-3-2013  70.25 

現在,我使用下面的查詢

SELECT * FROM (
(SELECT Table1.date, Table1.pprice AS P_Price, NULL AS D_Price FROM Table1) 
UNION ALL 
(SELECT Table2.date, NULL AS P_Price, Table2.dprice AS D_Price FROM Table2) 
) results 
ORDER BY date DESC 

這將導致以下輸出:

date   P_Price   D_Price 
25-3-2013  NULL    70.25 
25-3-2013  57.62   NULL 
17-2-2013  NULL    68.59 
15-2-2013  55.64   NULL 
22-1-2013  54.56   NULL 
12-1-2013  NULL    66.56 

在這種情況下,顯示25-3-2013的日期兩次以顯示一次P_Price和一次D_Price。我試圖讓日期行只出現一次,同時輸入的價格和沒有NULL像

date   P_Price   D_Price 
**25-3-2013  57.62   70.25** 
    17-2-2013  NULL    68.59 
    15-2-2013  55.64   NULL 
    22-1-2013  54.56   NULL 
    12-1-2013  NULL    66.56 

我怎麼能得到這個?

回答

3

不幸的是MySQL不支持FULL OUTER JOIN,但是你可以按照如下達到同樣的效果:

select t1.date, t1.pprice AS P_Price, t2.dprice AS D_Price 
from Table1 t1 
    left join table2 t2 on t1.date = t2.date 
union 
select t2.date, t1.pprice AS P_Price, t2.dprice AS D_Price 
from Table2 t2 
    left join table1 t1 on t2.date = t1.date 
+0

不錯,今天我學到了東西!!!! – user1974729

+0

這有效,但沒有按日期排序。訂單也可以嗎? – Ranadeep

+0

@Ranadeep - 你有沒有試過只加入'按日期排序desc'?它應該與'union'的結果一起工作。 – sgeddes

1

使用SUM和GROUP BY:

SELECT date, SUM(P_Price) AS P_Price, SUM(D_Price) AS D_Price 
FROM (SELECT Table1.date, Table1.pprice AS P_Price, NULL AS D_Price FROM Table1 
     UNION ALL 
     SELECT Table2.date, NULL AS P_Price, Table2.dprice AS D_Price FROM Table2 
    ) results 
GROUP BY date 
ORDER BY date DESC