简体   繁体   English

MySQL查询以获取每个类别中的最后一条记录

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM