【问题标题】:Merging 2 columns from 2 different tables into a single one将 2 个不同表中的 2 列合并为一个
【发布时间】:2016-07-18 17:53:56
【问题描述】:

我有 2 张桌子:

  • 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

这是我想要的:dayuser_idtypeitem_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),但并没有带来更好的结果。

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

谢谢,

日本

【问题讨论】:

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

标签: sql


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-10
    • 2021-10-29
    • 2014-08-04
    • 2016-03-10
    • 2018-10-30
    • 2012-04-13
    • 1970-01-01
    • 2013-03-24
    相关资源
    最近更新 更多