试试这个
SELECT
user_id
FROM
my_table
WHERE
purchase_date >= '2012-05-01' --your_start_date
GROUP BY
user_id
HAVING
max(purchase_date) <= '2012-06-01'; --your_end_date
它的工作原理是获取所有记录>= start date
,将结果集分组user_id
,然后找到max
每个用户的购买日期。购买日期max
应该是。<=end date
由于此查询不使用 ajoin/inner query
它可能会更快
测试数据
CREATE table user_purchases(user_id int, purchase_date date);
insert into user_purchases values (1, '2012-05-01');
insert into user_purchases values (2, '2012-05-06');
insert into user_purchases values (3, '2012-05-20');
insert into user_purchases values (4, '2012-06-01');
insert into user_purchases values (4, '2012-09-06');
insert into user_purchases values (1, '2012-09-06');
输出
| USER_ID |
-----------
| 2 |
| 3 |
SQLFIDDLE