[英]Mysql query GROUP BY where condition LIMIT 1
I have a table called "articles" on the database 我在数据库上有一个名为“articles”的表
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
I need a query to get the latest articles from the table BUT just ONE article for each Writer 我需要一个查询来获取表格中的最新文章,但每个作家只需要一篇文章
depends on the rows above the query should get just 3 rows : each article owns by ONE writer 取决于查询上面的行应该只有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 PHP
SELECT *
FROM articles
WHERE writer_id = ???? ;
order by id desc limit 10
thanks in advance : ) 提前致谢 : )
Using a combination of GROUP BY
and HAVING
will allow you to get the last article written by each author, and have them ordered properly: 使用
GROUP BY
和HAVING
的组合将允许您获取每位作者撰写的最后一篇文章,并正确地订购它们:
SELECT *
FROM articles
WHERE writer_id = ????
GROUP BY writer_id
HAVING id = MAX(id)
ORDER BY id DESC
LIMIT 10
短而甜蜜:
SELECT MAX(id), writer_id, title, text FROM articles GROUP BY writer_id;
Use a subquery to get the latest article id per writer: 使用子查询获取每个编写器的最新文章ID :
SELECT * FROM articles
WHERE id in
(
SELECT MAX(id) id, writer_id
FROM articles
GROUP BY writer_id
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.