MYSQL UNION ALL具有独特的行

时间:2013-07-06 20:56:36

标签: mysql

我有两张表如下:

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

我怎么能得到这个?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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