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只是它正在拉的帖子的时间戳。如何获得显示这些用户的最后一篇文章的表格?

4

1 回答 1

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
于 2013-10-12T03:00:48.703 回答