我通过以下方式请求最近6个月的客户:
SELECT customer
FROM table
WHERE date_of_last_order>date_sub(NOW(),INTERVAL 6 MONTH)
GROUP BY customer
ORDER BY customer ASC
现在,我还想要一份超过6个月的旧订单清单,但不应该包括最近6个月的客户。
有什么想法吗?谢谢!
答案 0 :(得分:4)
您要使用having
子句:
SELECT customer
FROM table
GROUP BY customer
HAVING MAX(date_of_last_order) <= date_sub(NOW(), INTERVAL 6 MONTH)
ORDER BY customer ASC
答案 1 :(得分:0)
由于未描述表结构,因此您需要date_of_last_order
<= 6个月的表结构。
SELECT customer
FROM table
WHERE date_of_last_order <= date_sub(NOW(), INTERVAL 6 MONTH)
GROUP BY customer
ORDER BY customer ASC
答案 2 :(得分:-1)
嗯... 您怎么看,戈登? HAVING
子句是否仅将“下游” 应用于到目前为止选择的行?
想到的另一种可能性是NOT IN
...
...
WHERE date_of_last_order>date_sub(NOW(),INTERVAL 6 MONTH)
AND customer NOT IN (
SELECT DISTINCT customer FROM table
WHERE date_of_last_order < date_sub(NOW(),INTERVAL 6 MONTH)
)
...
...尽管对我来说“肯定开始听起来很昂贵” 。我绝对希望将EXPLAIN
动词应用于我想到的各种替代方法,以发现MySQL认为最便宜的替代方法。