2013-05-27 73 views
5

一組由結果後,我有如下表,如何使用WHERE子句中的MySQL

mysql> select username,authdate from radpostauth; 
+------------+---------------------+ 
| username | authdate   | 
+------------+---------------------+ 
| timetest | 2013-05-21 22:44:46 | 
| timetest | 2013-05-21 23:54:20 | 
| coconeja | 2013-05-22 00:01:42 | 
| coconeja | 2013-05-22 00:06:35 | 
| coconeja | 2013-05-25 22:35:34 | 
| timetest | 2013-05-25 23:04:54 | 
| distom11 | 2013-05-25 23:10:47 | 
| distom11 | 2013-05-25 23:16:42 | 
| test  | 2013-05-25 23:45:16 | 
| pepe  | 2013-05-26 00:07:00 | 
| doce  | 2013-05-26 00:46:48 | 
| 6096753968 | 2013-05-26 01:42:30 | 
| 2269664468 | 2013-05-26 01:43:57 | 
| 2076877624 | 2013-05-26 02:01:53 | 
| 4446830988 | 2013-05-26 02:02:28 | 
| 2076877624 | 2013-05-26 02:08:53 | 
| 3906187975 | 2013-05-26 22:00:30 | 
| 3906187975 | 2013-05-26 22:21:44 | 
| kk   | 2013-05-26 22:32:20 | 
| kk   | 2013-05-26 22:44:19 | 
| 160059817 | 2013-05-27 00:53:56 | 
| yibced9 | 2013-05-27 13:32:00 | 
| yibced9 | 2013-05-27 13:37:53 | 
| yibced9 | 2013-05-27 13:38:01 | 
| yibced9 | 2013-05-27 13:38:02 | 
| yibced9 | 2013-05-27 13:38:03 | 
| yibced9 | 2013-05-27 13:38:39 | 
| yibced9 | 2013-05-27 13:38:40 | 
| yibced9 | 2013-05-27 13:38:41 | 
| yibced9 | 2013-05-27 13:44:40 | 

我想找到「用戶名」誰第一次訪問是在過去的12個小時。

我知道如何在第一時間拿到每個用戶已登錄使用以下查詢

mysql> select username,min(authdate) from radpostauth group by username; 
+------------+---------------------+ 
| username | min(authdate)  | 
+------------+---------------------+ 
| 160059817 | 2013-05-27 00:53:56 | 
| 2076877624 | 2013-05-26 02:01:53 | 
| 2269664468 | 2013-05-26 01:43:57 | 
| 3906187975 | 2013-05-26 22:00:30 | 
| 4446830988 | 2013-05-26 02:02:28 | 
| 6096753968 | 2013-05-26 01:42:30 | 
| coconeja | 2013-05-22 00:01:42 | 
| distom11 | 2013-05-25 23:10:47 | 
| doce  | 2013-05-26 00:46:48 | 
| kk   | 2013-05-26 22:32:20 | 
| pepe  | 2013-05-26 00:07:00 | 
| test  | 2013-05-25 23:45:16 | 
| timetest | 2013-05-21 22:44:46 | 
| yibced9 | 2013-05-27 13:32:00 | 
+------------+---------------------+ 

所以現在我triying讓這些用戶名這樣做:

select * 
from radpostauth 
where (
    select username,min(authdate) 
    from radpostauth group by username 
    ) > timediff(now(),maketime(12,0,0,)); 

但obviouly它不起作用...

回答

10
select username, min(authdate) 
from radpostauth 
group by username 
having min(authdate) > NOW() - INTERVAL 12 HOUR 

在SQL中,WHERE限制行,但是HAVING限制g roups。

+2

更像哪裏在行級別運行在掃描表,並有工作在結果集的水平,畢竟集合函數會計算其結果。 –

0

完美的答案是比爾這裏,但對於窮盡的緣故大衛的嘗試是值得修正:

SELECT * 
FROM (
    SELECT username, MIN(authdate) as min_authdate 
    FROM radpostauth 
    GROUP BY username 
) T 
WHERE min_authdate > NOW() - INTERVAL 12 HOUR;