连接两个表并合并mysql中的公共列

时间:2018-12-04 16:00:50

标签: mysql datetime join outer-join

我有2个mysql表:

t1 with columns as follows:
customer, datetime, products1
t2 with columns as follows:
customer, datetime, products2
t1: customer  datetime             products1  country
    111       2018-11-23 01:12:33    p1         A
    111       2018-11-23 01:13:00    p2         A   
    112       2018-11-23 01:12:12    p1         B
    112       2018-11-23 01:15:10    p3         B


t2: customer  datetime             products2
    111       2018-11-23 01:12:40    q1
    111       2018-11-23 01:13:00    q2
    112       2018-11-23 01:12:10    q1
    112       2018-11-23 01:15:20    q3

我想同时使用mysql和外部连接进行连接,并且只获得1个datetime,1个客户并合并这两个产品,最后按datetime进行订购。所以我想要这样的东西:

 customer         datetime              products    country
  112             2018-11-23 01:12:10     q1          NULL
  112             2018-11-23 01:12:12     p1          B
  111             2018-11-23 01:12:33     p1          A
  111             2018-11-23 01:12:40     q1          NULL
  111             2018-11-23 01:13:00     p2          A
  111             2018-11-23 01:13:00     q2          NULL
  112             2018-11-23 01:15:10     p3          B
  111             2018-11-23 01:13:00     q2          NULL

我只是想知道如何将两个日期时间合并为一个相同的产品。

1 个答案:

答案 0 :(得分:0)

由于两个表之间没有公共数据,因此我认为您想要的是UNION,而不是MERGE。试试这个:

SELECT
  customer,
  datetime,
  products1 as products,
  country
FROM t1
UNION
SELECT
  customer,
  datetime,
  products2 as products,
  null as country
FROM t2