假设您有下表:
+-----+-------+---------------------+
| uid | aid | time |
+-----+-------+---------------------+
| 187 | 20021 | 2016-07-19 03:05:06 |
| 167 | 20021 | 2016-07-19 03:05:06 |
| 155 | 20021 | 2016-07-19 03:05:06 |
| 154 | 20021 | 2016-07-19 03:05:06 |
| 155 | 20021 | 2016-07-18 03:05:06 |
| 138 | 20023 | 2016-07-16 05:25:00 |
| 140 | 20021 | 2016-07-16 05:05:18 |
| 153 | 20021 | 2016-07-16 05:04:41 |
| 146 | 20021 | 2016-07-16 05:04:33 |
| 152 | 20021 | 2016-07-16 05:04:27 |
| 151 | 20021 | 2016-07-16 05:04:22 |
| 150 | 20021 | 2016-07-16 05:04:16 |
| 148 | 20021 | 2016-07-16 05:04:10 |
| 147 | 20021 | 2016-07-16 03:29:55 |
| 140 | 20021 | 2016-07-16 02:12:13 |
| 139 | 20020 | 2016-07-16 02:11:53 |
| 154 | 20028 | 2016-07-13 05:04:47 |
| 167 | 20028 | 2016-07-13 05:04:47 |
| 154 | 20028 | 2016-07-12 05:04:47 |
| 137 | 20028 | 2016-07-12 05:04:47 |
+-----+-------+---------------------+
使用mysql快速获取在某个日期(可能是2016-07-19)首次出现的所有uid,但不是在日期之前。
结果表将是:
+-----+-------+---------------------+
| uid | aid | time |
+-----+-------+---------------------+
| 187 | 20021 | 2016-07-19 03:05:06 |
+-----+-------+---------------------+
继续在日期B中获得发生,在日期A中继续第一次出现。
样品: 在2016-07-19获取所有uid,并在2016-07-13首次出现
+-----+-------+---------------------+
| uid | aid | time |
+-----+-------+---------------------+
| 167 | 20021 | 2016-07-19 03:05:06 |
+-----+-------+---------------------+
提前感谢任何想法。
答案 0 :(得分:1)
假设您拥有正确的索引:
select t.*
from t
where time >= '2016-07-19' and time < '2016-07-20' and
not exists (select 1
from t t2
where t2.uid = t.uid and
t2.time < '2016-07-19'
);
您需要t(time)
和t(uid, time)
上的索引。
如果你只想要uid
,你也可以使用聚合:
select uid
from t
group by uid
having min(time) >= '2016-07-19' and min(time) < '2016-07-20';
我不认为MySQL会使用索引进行此查询。
答案 1 :(得分:0)
select uid from users
group by uid
having min(date(`time`)) = '2016-07-19