2016-06-08 77 views
0

我有一個表來記錄用戶上次登錄的詳細檢索最後一條記錄各組中沒有主鍵

event_name userID value     created_at 
------------------------------------------------------------- 
last_login 12 2016-06-02 11:06:29 2016-06-02 11:06:29 
last_login 12 2016-06-02 10:16:11 2016-06-02 10:16:11  
last_login 14 2016-06-02 10:11:13 2016-06-02 10:11:13  
last_login 17 2016-05-02 10:16:29 2016-05-02 10:16:29  
last_login 14 2016-05-02 10:15:11 2016-06-02 10:15:11  

預期結果:

event_name userID value     created_at 
------------------------------------------------------------- 
last_login 12 2016-06-02 11:06:29 2016-06-02 11:06:29 
last_login 14 2016-06-02 10:11:13 2016-06-02 10:11:13  
last_login 17 2016-05-02 10:16:29 2016-05-02 10:16:29  

我要搶的用戶ID此表信息組,我通過created_at命令並顯示timesAgo fromat(例如1小時前)的值,但是我沒有獲得使用group的最新記錄,例如,對於userID = 12,我得到的值= 2016-06-02 10:16: 11而不是值= 2016-06-02 11:06:29

+0

還指定預期的結果! – jarlh

+0

什麼是你的SQL查詢? – Igoranze

+0

你使用什麼數據庫數據類型作爲'value'? –

回答

1

如果我理解正確的話,你可以用NOT EXISTS()實現這一目標:

SELECT * FROM YourTable t 
WHERE NOT EXISTS(SELECT 1 FROM YourTable s 
       WHERE s.created_at > t.created_at 
        AND s.userID = t.userID) 
+0

我想我沒有讓自己明確的問題,我已經添加了預期的結果,使其更清楚我需要什麼 –

+0

對不起,還是不明白,爲什麼有一次你選擇最大的日期,一次是最小的?! @KuldeepDangi – sagi

+0

記錄由'USERID' –

1

試試這個。

首先,我從created_at和用戶ID獲得最大,然後我加入讓孔列

SELECT d.* FROM (
    SELECT 
     userID, MAX(created_at) AS created_at 
    FROM 
     tablename 
    GROUP BY userID) AS `keys` 
LEFT JOIN tablename d ON 
    d.userID = `keys`.userID 
    AND 
d.created_at = `keys`.created_at; 

樣品

MariaDB []> SELECT d.* FROM (
    -> SELECT 
    ->  userID, MAX(created_at) AS created_at 
    -> FROM 
    ->  tablename 
    -> GROUP BY userID) AS `keys` 
    -> LEFT JOIN tablename d ON 
    -> d.userID = `keys`.userID 
    -> AND 
    -> d.created_at = `keys`.created_at; 
+--------+----------------------------+ 
| userID | created_at     | 
+--------+----------------------------+ 
|  1 | 0000-00-00 00:00:00.000000 | 
|  2 | 2016-06-03 13:16:07.000000 | 
+--------+----------------------------+ 
2 rows in set (0.00 sec) 

MariaDB []> 
+0

在mysql中運行這個查詢導致語法錯誤'near AS keys' –

+0

@Kuldeep Dangi - 抱歉 - 我的錯誤 - 第一:keys是一個關鍵字,必須反引用或使用其他別名。第二:我忘記了max(created_date)的別名。我已經改變了我的答案。請再次測試 - 對不起 –

+0

現在它的工作很酷 –

相關問題