我目前正在尝试根据为主题提交的回复数量来获取论坛主题。虽然我已经习惯使用SQL一段时间了,但我对理解SQL如何工作有些新意,尽管我觉得我在正确的轨道上。我目前有这个问题:
SELECT * FROM `topics`
INNER JOIN (
SELECT COUNT(tid) as countedReplies,`tid`
FROM `replies`
GROUP BY `tid`
)
ON topics.id = replies.tid
ORDER by replies.countedReplies DESC
表结构如下所示:
主题
ID Topic Name
1 Filler Topic Name
2 Exciting Posts about Excellence
3 Random name for example
回复
ID tid Post
1 3 Hooray! Wonderful!
2 3 I am a post to topic id 3 as well!
3 1 Topic 1 is better than topic 1.
我的预期结果
我没有得到任何回报,虽然我想得到这样的东西:
1. Random name for example
2. Filler Topic Name
3. Exciting Posts about Excellence
答案 0 :(得分:1)
您可以使用左连接而不涉及任何子选择
SELECT t.* FROM `topics` t
LEFT JOIN `replies` r
ON t.id = r.tid
GROUP BY t.id
ORDER by count(r.tid) DESC