[英]Mysql Select events from last year but not this year
I need some direction on a query. 我需要查询的一些方向。
I have an orders table. 我有一个订单表。 It has the following columns (among others) 它具有以下列(以及其他列)
OrderID | OrderDate | CustomerID
I want to find customers who ordered in 2012, but have not ordered in 2013. 我想找到在2012年订购但在2013年未订购的客户。
(and actually I will eventually want more precision (customers who ordered in March of 2012, but not 2013)) (实际上,我最终会希望获得更高的精度(2012年3月而不是2013年订购的客户))
I know I could do two queries - 我知道我可以做两个查询-
"SELECT * FROM TABLE WHERE OrderDate BETWEEN 2012-01-01 AND 2012-12-31"
"SELECT * FROM TABLE WHERE OrderDate BETWEEN 2013-01-01 AND 2013-12-31"
and then analyze the results, but it seems like it ought to be possible with pure mysql. 然后分析结果,但纯mysql似乎应该可以实现。
Perhaps a self join? 也许是自我加入? Or a nested SELECT? 还是嵌套的SELECT? I'm not very familiar with these and am having a hard time finding a relevant example. 我对这些不是很熟悉,并且很难找到一个相关的例子。 Thanks for your help! 谢谢你的帮助!
No joins required; 无需加入; just filter the orders when grouped on customer: 仅在按客户分组时过滤订单:
SELECT CustomerID
FROM Orders
GROUP BY CustomerID
HAVING SUM(OrderDate BETWEEN 2012-03-01 AND 2012-03-31)
AND NOT SUM(OrderDate BETWEEN 2013-01-01 AND 2013-12-31)
eggyal's answer will work, but it could be very slow since it can't make use of indexes. eggyal的答案会起作用,但是由于它不能利用索引,因此它可能会很慢。 Assuming you have an index on OrderDate
, the following self-JOIN may be better: 假设您在OrderDate
上有一个索引,则以下自我联接可能会更好:
SELECT DISTINCT o1.CustomerID
FROM Orders o1
LEFT JOIN Orders o2
ON o1.CustomerID = o2.CustomerID
AND o2.OrderDate BETWEEN '2013-01-01' AND '2013-12-31 23:59:59'
WHERE o1.Orderdate BETWEEN '2012-01-01' AND '2012-12-31 23:59:59'
AND o2.CustomerID IS NULL
My query is more readable. 我的查询更具可读性。 Just subtraction customers of 2013 from customers of 2012. 从2012年的客户中减去2013年的客户。
SELECT `CustomerID`
FROM `d`
WHERE
`OrderDate` BETWEEN '2012-01-01' AND '2012-12-31 23:59:59'
AND `CustomerID` NOT IN
(SELECT `CustomerID`
FROM `d`
WHERE
`OrderDate` BETWEEN '2013-01-01' AND '2013-12-31 23:59:59'
GROUP BY `CustomerID`)
GROUP BY `CustomerID`
And there is some info about how to rewrite query with subquery to query with join (@Barmar's solution). 还有一些有关如何使用子查询重写查询以使用join查询的信息 (@Barmar解决方案)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.