[英]MySQL query to get last record in each category
I got two tables: articles and categories (about 20 categories), and I want to get the lastest 10 articles, but no more than one from a category. 我有两个表: 文章和类别 (大约20个类别),我想得到最新的10篇文章,但不超过一个类别。
Table Articles 表文章
id | title | text
Table Categories 表类别
id | name
Table ArticlesCategories (relationsl table between Articles and Categories) 表ArticlesCategories (文章和类别之间的关系表)
article | category
Im using the query below but the problem is that the 10 results are not all the latest articles. 我使用下面的查询,但问题是10结果不是所有最新的文章。
SELECT id, title, categoryId, categoryName
FROM (
SELECT a.id, a.title, ac.category AS categoryId, c.name AS categoryName
FROM articles AS a
LEFT JOIN articles_categories AS ac ON ac.article = a.id
LEFT JOIN categories AS c ON c.id = ac.category
WHERE ac.priority = 1
ORDER BY a.id DESC ) AS tmp_table
GROUP BY categoryId LIMIT 10
Add ORDER BY id DESC
to your query 将ORDER BY id DESC
添加到您的查询中
This is the way of getting the last 10 rows is to reverse the order and select the first ten rows: 这是获取最后10行的方法是颠倒顺序并选择前十行:
SELECT id, title, categoryId, categoryName
FROM (
SELECT a.id, a.title, ac.category AS categoryId, c.name AS categoryName
FROM articles AS a
LEFT JOIN articles_categories AS ac ON ac.article = a.id
LEFT JOIN categories AS c ON c.id = ac.category
WHERE ac.priority = 1
ORDER BY a.id DESC ) AS tmp_table
GROUP BY categoryId ORDER BY id DESC LIMIT 10
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.