在一个表中混合2个查询的结果?

时间:2018-12-14 16:20:02

标签: sql merge ms-access-2007

我是SQL的新手,我可以将两个查询的结果混合在一个具有不同属性的表中吗?

在我的数据库的3个表下面,我想要得到的结果。这可能吗?

客户端

|id|name|adress|
----------------
|1 |a   |x     |
|2 |b   |y     |

订单

|id|client.id|product|date     |
--------------------------------
|1 |1        |px     |2018-01-1|
|2 |1        |py     |2018-05-1|
|3 |2        |px     |2018-06-1|

付款

|id|client.id|amount|date     |
-------------------------------
|1 |1        |1000  |2018-03-1|
|2 |2        |500   |2018-09-1|

输出

|name |order.id |product |pay.id |amount |date     |
----------------------------------------------------
|a    |1        |px      |-      |-      |2018-01-1|
|a    |-        |-       |1      |1000   |2018-03-1|
|a    |2        |py      |-      |-      |2018-05-1|
|b    |3        |px      |-      |-      |2018-06-1|
|b    |-        |-       |2      |500    |2018-09-1|

1 个答案:

答案 0 :(得分:2)

已编辑以进行访问。
UNION用于2个子查询:

SELECT * FROM (
  SELECT client.name, order.id AS orderid, order.product AS product, 
    "-" AS payid, "-" AS amount, order.date AS [date]
  FROM client INNER JOIN [order] ON client.id = order.clientid
  UNION
  SELECT client.name, "-" AS orderid, "-" AS product, 
    pay.id AS payid, pay.amount AS amount, pay.date AS [date]
  FROM client INNER JOIN [pay] ON client.id = pay.clientid
  )
ORDER BY name, date

结果是:

name    orderid product payid   amount  date
a         1       px      -       -     2018-01-1
a         -       -       1      1000   2018-03-1
a         2       py      -       -     2018-05-1
b         3       px      -       -     2018-06-1
b         -       -       2      500    2018-09-1