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

时间:2016-07-18 17:53:57

标签: sql

我有两张桌子:

  • 1对于商店里的人的访问
  • 这些访客购买
  • 1

因此买家也必须是访客。

以下是我的数据:

PURCHASE_TABLE

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

VISIT_TABLE

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 user_id type item_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

与我在此处找到的内容相似:How can I merge the columns from two tables into one output? 我认为它不起作用,因为我使用的是两个表之间不同的列。

我尝试了JOIN(INNER和LEFT),但没有带来更好的结果。

你对我如何得到我想要的结果有什么想法吗?

谢谢,

JP

1 个答案:

答案 0 :(得分:3)

您希望显示两个表的所有行,您可以使用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"