我在数据库中有一个名为“articles”的表
文章:
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
提前感谢:)
答案 0 :(得分:1)
使用GROUP BY
和HAVING
的组合,您可以获得每位作者撰写的最后一篇文章,并让他们正确订购:
SELECT *
FROM articles
WHERE writer_id = ????
GROUP BY writer_id
HAVING id = MAX(id)
ORDER BY id DESC
LIMIT 10
答案 1 :(得分:1)
短而甜蜜:
SELECT MAX(id), writer_id, title, text FROM articles GROUP BY writer_id;
答案 2 :(得分:0)
使用子查询获取每个作者的最新文章ID :
SELECT * FROM articles
WHERE id in
(
SELECT MAX(id) id, writer_id
FROM articles
GROUP BY writer_id
)