加入 3 个表以查找购买某个商品的新用户

问题描述

我无法加入 2 个表格,以便我查看哪些新客户至少购买了 1 个特定商品。第一个从特定日期范围拉取新客户帐户,第二个拉取在特定日期范围内至少购买过商品的客户

select customer.id from customer c
inner join device d on u.id = d.user_id
where c.created_date between {{start}} and {{end}}
group by c.id

select customer_id from purchase_history 
where item_id = {{itemID}} and created_date between {{starts}} and {{ends}} group by customer_id

我被连接部分困住了,这总是让我感到困惑,但这是我现在所拥有的:

select customer.id from customer c 
INNER JOIN device d on u.id = d.user_id 
INNER JOIN
     (select customer_id from purchase_history 
where item_id = {{itemID}}
     ) c
     on c.customer = customer_id.purchase_history
where created_date between {{starts}} and {{ends}} 
group by customer_id

谢谢!!

主要目标是提供一个日期范围和一个项目 ID,然后该 ID 将拉出在特定日期范围内购买该特定项目(第二个代码)的新客户(第一个代码)列表。三个表(客户、设备和购买历史)都包含客户 ID 列。

解决方法

这个怎么样:

select id
from customer c
  INNER JOIN device d on d.user_id = c.id
  INNER JOIN purchase_history ph on c.id = ph.customer_id
where ph.item_id = {{itemID}}
  and ph.created_date between {{starts}} and {{ends}} 
group by ph.customer_id

如果这没有帮助,也许您可​​以提供您加入的每张桌子的示例以及您想要的内容。从您发布的内容来看,您似乎只需要客户 ID。