sql join两个表,一个是摘要,另一个是详细信息

时间:2016-05-25 06:47:50

标签: mysql sql

当连接两个表时,我不知道如何将以下表格加入到我想要的中。

表A:

--------------------------------------
|   id |   name |  buy time | total |
--------------------------------------
|    1 |    A   |    3      |   30  |
--------------------------------------
|    2 |    B   |    1      |   10  |
--------------------------------------

表B:

-------------------------------
|   id |  orderid | price  |
-------------------------------
|   1  |     1    |   10   |
-------------------------------
|   1  |     2    |   10   |
-------------------------------
|   1  |     3    |   10   |
-------------------------------
|   2  |     4    |   10   |
-------------------------------

加入表C

---------------------------------------------------------
|  id |  name  |  buy time |  total |  orderid |  price |
---------------------------------------------------------
|   1 |    A   |     3     |    30  |          |        |
---------------------------------------------------------
|   1 |        |           |        |    1     |   10   |
---------------------------------------------------------
|   1 |        |           |        |    2     |   10   |
---------------------------------------------------------
|   1 |        |           |        |    3     |   10   |
---------------------------------------------------------
|   2 |    B   |     1     |    10  |          |        |
---------------------------------------------------------
|   2 |        |           |        |    4     |   10   |
---------------------------------------------------------

如果我在A.id = B.id"上使用" Left OUT JOIN 空白区域将填充重复值,导致总收入总和不正确

另一种方法是"从B"中选择0作为名称,用0填充空白,如果列数太多,这将是一场灾难。

因此,我想请求帮助是否有更好的方法来实现我的目标?

4 个答案:

答案 0 :(得分:3)

你真正想要的是两个表的UNION

SELECT id, name, `buy time`, total, null AS orderid, null AS price
FROM A

UNION 

SELECT id, null, null, null, orderid, price
FROM B
ORDER BY id, name DESC, orderid

Demo here

答案 1 :(得分:1)

您似乎需要UNION ALL

SELECT `id`,`name`,`buy time`,`total`,null,null
FROM TableA 
UNION ALL
SELECT id,null,null,null,orderid,price
FROM TableB 
ORDER BY `id`,`name` ,orderid

无需进行此类不必要的连接,因为您没有以任何方式将它们彼此连接。

答案 2 :(得分:0)

看起来你需要使用UNION

select id, name, `buy time`, total, null AS orderid, null AS price
from A
UNION 
select id, null, null, null, orderid, price
from B
order by id, name DESC

答案 3 :(得分:0)

选择ID,名称,购买时间,总计,订单,价格 (

  SELECT  [id]
 , null as [orderid]
  ,null as [price],
   [name]
  ,[buytime]
  ,[total]
   FROM A
     UNION

 SELECT [id]
  ,[orderid]
  ,[price],
  null as[name]
  , null as[buytime]
  ,null as [total]
 FROM B

)aa