我有两个表:文章和类别(大约20个类别),我想获得最新的10篇文章,但不超过一个类别。
表文章
id | title | text
表类别
id | name
表 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
答案 0 :(得分:2)
将ORDER BY id DESC
添加到您的查询
这是获取最后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