我想获得在主题中发表评论的最后10位用户。
它没有按预期工作。
SELECT DISTINCT
p.author, a.name
FROM posts p
INNER JOIN users a
ON a.id = p.author
AND topicId = ?
ORDER BY p.id
DESC LIMIT 10'
SELECT p.author, a.name
FROM posts.p
INNER JOIN users a
ON a.id = p.author
AND topicId = ?
GROUP BY p.author
ORDER BY p.id
DESC LIMIT 10
这不起作用。我通过与订单组合来尝试组。但那也不起作用..有什么建议吗?
结果与id索引不匹配。
发布表内容如下所示:
POST 1 -> user 1
POST 2 -> user 2
POST 3 -> user 3
结果:
2,1 etc.
订购错误。
答案 0 :(得分:0)
这应该会让你获得前10名。
Select a.author, a.name
from users a
inner join (select top 10 id from posts group by id order by id desc) as posts
on posts.id = a.author
where topicID = ?
答案 1 :(得分:0)
如果我理解正确,我认为这会做你想要的:
SELECT p.author, a.name
FROM posts p INNER JOIN
users a
ON a.id = p.author AND topicId = ?
GROUP BY p.author, a.name
ORDER BY max(p.id) DESC
LIMIT 10;
此查询与您的查询之间的主要区别始于显式聚合。 order by
然后使用max(p.id)
进行排序。通过仅使用p.id
,MySQL从匹配的行中选择任意id
- 并且可能是出于您的目的而错误的。{/ p>