我有一张桌子,比方说,就像这样:
|--------------------------------------+--------------------------------------+--------+----------------+---------------------|
| user_id | mortgage_id | value | classification | created_at |
|--------------------------------------+--------------------------------------+--------+----------------+---------------------|
| 6c1e1f12-2e5d-488d-b02d-29fcffe783f2 | 1e76bcbb-70ee-4966-87fd-1d6024a04513 | 0 | initial | 2014-08-23 14:25:42 |
|--------------------------------------+--------------------------------------+--------+----------------+---------------------|
| 49dc3dab-d2d0-400b-b964-71e03339d475 | 59366911-f1a8-4a8c-b7ea-c3257d04478e | 1 | created | 2015-08-23 14:26:11 |
|--------------------------------------+--------------------------------------+--------+----------------+---------------------|
| 76ce889b-2f2c-435f-8754-7c5ec15cbfcb | b962e26b-1ba6-4547-8eb8-167989a0705e | 5 | created | 2016-08-23 14:26:11 |
|--------------------------------------+--------------------------------------+--------+----------------+---------------------|
| 5d9f1892-05c0-4b0a-b5d9-a501595fa351 | fb4be36e-e156-4c1b-bd40-422d30646f8e | 8 | created | 2016-08-23 14:26:11 |
|--------------------------------------+--------------------------------------+--------+----------------+---------------------|
| 49dc3dab-d2d0-400b-b964-71e03339d475 | 2cee0bc7-744f-4f51-a094-f5eb66ac482e | 2 | created | 2017-08-23 14:26:11 |
|--------------------------------------+--------------------------------------+--------+----------------+---------------------|
| 76ce889b-2f2c-435f-8754-7c5ec15cbfcb | b0d27c9e-907c-43df-abd2-5772785cb91c | 0 | created | 2017-08-23 14:26:11 |
|--------------------------------------+--------------------------------------+--------+----------------+---------------------|
我正在尝试获取/获取所有在特定时刻及之后没有任何记录的不同/唯一
user_id
。
例如,如果我选择“时间范围”为:After 2017-01-01 00:00:00
,则返回值为:
|--------------------------------------+
| user_id |
|--------------------------------------+
| 6c1e1f12-2e5d-488d-b02d-29fcffe783f2 |
|--------------------------------------+
| 5d9f1892-05c0-4b0a-b5d9-a501595fa351 |
|--------------------------------------+
我有这个查询,但我认为应该有更好的方法来做到这一点:
SET @timestamp = '2017-01-01 00:00:00';
SELECT DISTINCT user_id
FROM mortgages
WHERE user_id NOT IN (SELECT DISTINCT user_id FROM mortgages WHERE created_at > @timestamp);
答案 0 :(得分:2)
我会使用group by
:
select user_id
from mortgages
group by user_id
having max(created_at) <= @timestamp;