3

我在数据库上有一个名为“文章”的表

文章:

id +++   writer_id    +++     title     ++++    text
----------------------------------------------------
1           1              some title        article for writer 1 
2           1              some title        article for writer 1 
3           2              some title        article for writer 2 
4           2              some title        article for writer 2 
5           2              some title        article for writer 2
6           3              some title        article for writer 3

我需要一个查询来从表中获取最新文章,但每个作家只有一篇文章

取决于查询上方的行应该只有 3 行:每篇文章由一位作者拥有

2           1              some title        article for writer 1 
5           2              some title        article for writer 2
6           3              some title        article for writer 3

php

SELECT * 
FROM articles
WHERE writer_id = ???? ;
order by id desc limit 10

提前致谢 : )

4

3 回答 3

1

简短而甜蜜:

SELECT MAX(id), writer_id, title, text FROM articles GROUP BY writer_id;
于 2012-08-03T21:54:18.993 回答
1

使用GROUP BY和的组合HAVING将允许您获得每位作者撰写的最后一篇文章,并正确排序:

SELECT * 
FROM articles
WHERE writer_id = ????
GROUP BY writer_id
HAVING id = MAX(id)
ORDER BY id DESC
LIMIT 10
于 2012-08-03T21:49:07.333 回答
0

使用子查询获取每个作者的最新文章 ID

SELECT * FROM articles
WHERE id in
(
    SELECT MAX(id) id, writer_id
    FROM articles
    GROUP BY writer_id
)
于 2012-08-03T21:49:54.333 回答