gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:05:53 25 4
gpt4 key购买 nike

我有两个表:文章类别(大约20个类别),我想获取最新的10篇文章,但一个类别中不超过一篇。

表格文章

id | title | text

表格类别

id | name

Table ArticlesCategories(文章和类别之间的关系表)

article | category

我使用下面的查询,但问题是这 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

最佳答案

ORDER BY id DESC 添加到您的查询

获取最后 10 行的方法是颠倒顺序并选择前 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

关于MySQL查询获取每个类别中的最后一条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22742944/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com