1

我有两个表如下:

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

我怎样才能得到这个?

4

2 回答 2

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
于 2013-07-06T21:02:49.650 回答
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
于 2013-07-06T21:02:35.867 回答