简体   繁体   English

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

[英]Joining two tables and merging the common columns in mysql

I have 2 mysql tables: 我有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

I would like to join both as doing and outer join with mysql and get only 1 datetime, 1 customer and merge both products and finally order by datetime. 我想同时加入和通过mysql与外部连接,仅获得1个datetime,1个客户并合并这两个产品,最后按datetime订购。 So I want something like this: 所以我想要这样的事情:

 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

I am just wondering about how to merge the two datetimes into only one and same for products. 我只是想知道如何将两个日期时间合并为一个相同的产品。

Since there's no common data between the two tables, I think you want a UNION , not a MERGE . 由于两个表之间没有公共数据,我认为您需要一个UNION而不是MERGE Try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM