2017-09-29 38 views
0

我有一個表後行,讓我們說,像這樣的:選擇標識(相同的表)沒有任何記錄/特定日期

|--------------------------------------+--------------------------------------+--------+----------------+---------------------| 
| 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); 

回答

2

我會用group by

select user_id 
from mortgages 
group by user_id 
having max(created_at) <= @timestamp; 
相關問題