Sql 将2个不同表中的2列合并到一个表中

Sql 将2个不同表中的2列合并到一个表中,sql,Sql,我有两张桌子: 1用于商店内人员的参观 1用于这些访客的购买 因此,买家也必须是访客 以下是我掌握的数据: PURCHASE_TABLE day user_id_purchase item_id_purchase Type ---------- ---------------- ---------------- -------- 26/05/2016 AAA 47332 Purchase

我有两张桌子:

  • 1用于商店内人员的参观
  • 1用于这些访客的购买
因此,买家也必须是访客

以下是我掌握的数据:

PURCHASE_TABLE

day         user_id_purchase  item_id_purchase  Type    
----------  ----------------  ----------------  --------    
26/05/2016  AAA               47332             Purchase        
19/05/2016  BBB               46523             Purchase        
探视表

day         user_id_visit  Type
----------  -------------  -----
18/06/2016  AAA            Visit    
26/05/2016  AAA            Visit    
19/05/2016  BBB            Visit    
18/05/2016  CCC            Visit
以下是我想要的:
day
用户id
类型
项目id
从两张桌子

结果如下:

day         user_id  type      item_id
----------  -------  --------  -------
18/06/2016  AAA      Visit  
26/05/2016  AAA      Visit  
19/05/2016  BBB      Visit  
18/05/2016  CCC      Visit  
26/05/2016  AAA      Purchase  47332
19/05/2016  BBB      Purchase  46523
然而,我无法做到这一点。我得到的结果是到目前为止行数的乘积:我得到了4行(访问)*2行(购买),而不是4行+2行。事实上,我得到了每一次购买和每一次购买点击

以下是我使用的查询:

SELECT
  visits.user_id,
  coalesce(visits.day_visit, purchases.day_purchase) AS day,
  coalesce(visits.type, purchases.type) AS type,
  purchases.item_id_purchase
FROM
  (SELECT DISTINCT
     day          AS day_visit,
     user_id AS user_id,
     'Visit'    AS type
   FROM visit 
    WHERE DAY >= '2016-01-01') visits,
  (SELECT DISTINCT
     day          AS day_purchase,
     user_id_slow AS user_id,
     item_id      AS item_id_purchase,
     'Purchase'      AS type
   FROM purchase
   WHERE AND Day >= '2016-05-02') purchases
WHERE visits.user_id_display = purchases.user_id
与我在这里发现的更多或更少相似: 我认为它不起作用,因为我使用的是两个表之间不同的列

我也尝试了连接(内部和左侧),但并没有带来更好的结果

你知道我怎样才能得到我想要的结果吗

谢谢


JP

您希望显示两个表的所有行,可以使用
UNION
并从
Visit
表中伪造缺少的列

SELECT day_date, user_id, type, NULL AS item_id
FROM Visit
UNION 
SELECT day_date, user_id, type, item_id
FROM Purchase
ORDER BY  type DESC, user_id ASC , day_date ASC
结果是什么

day_date     user_id type        item_id
------------ ------- ----------  ------- 
"18-06-2016" "AAA"   "Visit"     "NULL"
"26-05-2016" "AAA"   "Visit"     "NULL"
"19-05-2016" "BBB"   "Visit"     "NULL"
"18-05-2016" "CCC"   "Visit"     "NULL"
"26-05-2016" "AAA"   "Purchase"  "47332" 
"19-05-2016" "BBB"   "Purchase"  "46523"

您需要在主
select
子句中指定什么是
distinct
。不仅仅是
from
子句中与您的
join
数据不同的内容。