我需要通过连接两个表来正确获取sql语句的帮助。
我的目标是针对customer_id
为空的给定产品返回在某些购买日期之间的购买次数。表Purchases
的外键是prospect_id
,对应于id
Prospect
在单独的SQL语句中,我将得到以下内容:
SELECT COUNT (id) FROM Purchases
WHERE (purchasedate BETWEEN '5/1/18' AND '12/31/18')
AND (product = 'Scooter')
SELECT id
from Prospect
where customer_id is null
因此,我提出了这样的查询:
SELECT COUNT (id)
FROM Purchases
LEFT JOIN Prospect
ON Prospect.id = Purchases.prospect_id
AND (Purchases.purchasedate BETWEEN '5/1/18' AND '12/31/18')
AND Purchases.product = 'Scooter'
AND Prospect.customer_id is null;
但随后出现错误:列引用“ id”不明确。
答案 0 :(得分:2)
使用count(*)
:
SELECT COUNT(*)
FROM Purchases pu LEFT JOIN
Prospect pr
ON pr.id = pu.prospect_id AND
pr.customer_id is null
WHERE pu.purchasedate >= '2018-05-01' AND
pu.purchasedate < '2019-01-01' AND
pu.product = 'Scooter';
我对查询做了一些更改。
首先,purchase
上的条件位于where
子句中,而不是on
子句中。大概您实际上希望它们成为过滤器。
第二,日期使用正确的格式YYYY-MM-DD。
我还用显式比较替换了between
。这意味着即使“日期”列具有时间成分,代码也可以工作。
最后,我还介绍了表别名。
答案 1 :(得分:2)
发生错误的原因是,您没有定义要计数的“ id”字段来自哪个表。
SELECT
COUNT(PURCHASES.ID) AS PURCHASE_COUNT
FROM
Purchases
LEFT JOIN Prospect
ON Prospect.id = Purchases.prospect_id
AND (Purchases.purchasedate BETWEEN '5/1/18' AND '12/31/18')
AND Purchases.product = 'Scooter'
AND Prospect.customer_id is null;