2013-10-12 119 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' –