SQL Select加入同一个表(按大多数回复排序)

时间:2014-09-20 12:21:00

标签: mysql sql join

所以我想从“board_b”中选择回复最多的帖子。我的问题是回复实际上在同一个表中。看看这个:

+---+-----------+---------+
|ID | name      | replyto |
+---+-----------+---------+
| 1 | newthread |         |
| 2 | reply     | 1       |
+---+-----------+---------+

(注意:名称列未设置为那些,只是为了演示)如您所见,1是一个新线程,2是回复1。现在我有一个充满了这些的表,并且表中有更多的列(文本,时间戳等等),但总的想法就像上面那样。

我想要实现的是选择所有线程,并按大多数回复排序(并且还限制为0,20)。我已经尝试过加入表格,但这对我来说太复杂了,所以示例代码会很棒。

3 个答案:

答案 0 :(得分:1)

这样的事情会做到:

SELECT board.id, board.name, COUNT(reply.id)
FROM board_b board INNER JOIN board_b reply ON board.id = reply.replyto
GROUP BY board.id, board.name
ORDER BY COUNT(reply.id) desc
LIMIT 20

答案 1 :(得分:0)

您想使用group by

select replyto as thread, count(*) as cnt
from board_b
group by replyto
order by cnt desc
limit 0, 20;

答案 2 :(得分:0)

select c.replyto, c.replycount
from
(
    select a.replyto as replyto, count(*) as replycount
    from board_b a
    inner join (
                select id, name, replyto
                from board_b
                where replyto is null
                ) b
        on b.id = a.replyto
    group by a.replyto
) c
where c.replycount between 0 and 20
order by c.replycount desc