2013-10-12 160 views
1

我有兩個表格,用戶和帖子。我試圖編寫一個查詢來查找用戶的最新帖子,但我遇到了麻煩。這是迄今爲止我所擁有的。獲取最近的帖子

select a.username, b.last_post from logins as a join (select login_id, entry as last_post from posts) as b where a.id = b.login_id

+-----------+---------------------+ 
| username | last_post   | 
+-----------+---------------------+ 
| something | 2013-10-08 22:12:00 | 
| other  | 2013-10-08 22:13:00 | 
| test  | 2013-10-08 22:13:03 | 
| test  | 2013-10-08 22:14:20 | 
| hello  | 2013-10-08 22:12:53 | 
| hello  | 2013-10-08 22:12:56 | 
+-----------+----------+----------+ 

所以現在last_post僅僅是它的拉後的時間戳。我如何獲得一個表格,只顯示這些用戶的最新帖子?

回答

3

,如果你只需要兩列,你可以直接使用MAX()

SELECT a.username, 
     MAX(b.entry) last_post 
FROM logins a 
     INNER JOIN posts b 
     ON a.id = b.login_id 
GROUP BY a.username 

否則,如果你想顯示在所有表中的所有列,可以有子查詢其分別獲取最新entry爲每login_id

SELECT a.*, b.* 
FROM logins a 
     INNER JOIN posts b 
      ON a.id = b.login_id 
     INNER JOIN 
     (
      SELECT login_id, MAX(entry) entry 
      FROM posts 
      GROUP BY login_id 
     ) c ON b.login_id = c.login_id AND 
       b.entry = c.entry 
+0

謝謝!你能解釋在第一個查詢中使用「group by」,但不能在第二個查詢中使用?順便說一句,我用了第二個。 – bvpx

+1

它簡單地通過'username'對記錄進行分組,並且對於每個用戶,它使用MAX()獲取最新的'entry' –