按帖子数量排序帖子

时间:2011-11-30 01:31:56

标签: mysql

我有一个有线程的表和一个有帖子的表。我想按照与他们相关联的帖子的数量列出这些。

我的表格的示例结构

帖子表:

id   creator    replyTo    text    timestamp
1    1          1          Bla     2011-11-11 11:11
2    2          2          Alb     2011-11-11 11:11
3    3          3          Lba     2011-11-11 11:11
4    4          1          Lab     2011-11-11 11:11
5    5          2          Bal     2011-11-11 11:11
6    2          2          Abl     2011-11-11 11:11

主题表:

id  creator     name       content    timestamp
1   1           BlaBla     BlaBla     2011-11-11 11:11
2   3           AlbAlb     AlbAlb     2011-11-11 11:11
3   2           LbaLba     LbaLab     2011-11-11 11:11

示例输出:

id  creator     name       count      timestamp
2   3           AlbAlb     3          2011-11-11 11:11
1   1           BlaBla     2          2011-11-11 11:11
3   2           LbaLba     1          2011-11-11 11:11

4 个答案:

答案 0 :(得分:2)

试试这个:

SELECT t.id, t.creator, t.name, count(*) AS ct, t.timestamp
FROM   threads t
JOIN   posts p ON p.replyTo = t.id
GROUP  BY 1
ORDER  BY count(*) DESC, 1,2;

完全生成所要求的结果。
请参阅working demo here

GROUP  BY 1

是简称(因为它足以按mysql中的主键分组):

GROUP  BY 1,2,3,5

这是(因为这些是位置参数)的缩写:

GROUP  BY t.id, t.creator, t.name, t.timestamp

回答评论中的其他问题

像这样添加WHERE子句:

SELECT t.id, t.creator, t.name, count(*) AS ct, t.timestamp
FROM   threads t
JOIN   posts p ON p.replyTo = t.id
WHERE  t.timestamp BETWEEN (CURRENT_TIMESTAMP - INTERVAL 24 HOUR)
                       AND CURRENT_TIMESTAMP 
GROUP  BY 1
ORDER  BY count(*) DESC, 1,2;

答案 1 :(得分:1)

SELECT t.id, t.creator, t.name, COUNT(1) AS postCount, t.timestamp
FROM threads AS t
INNER JOIN posts AS p ON t.id = p.replyTo
GROUP BY t.id, t.creator, t.name, t.timestamp
ORDER BY COUNT(1) DESC

答案 2 :(得分:1)

SELECT 
 t.id, t.creator, t.name, count(p.id) as count, t.timestamp
FROM
 threads t
  INNER JOIN posts p ON
    t.id = p.replyTo
GROUP BY
 t.id, t.creator, t.name, t.timestamp
ORDER BY 
 count DESC

答案 3 :(得分:1)

SELECT Threads.*, COUNT(*) post_count
FROM Threads LEFT JOIN Posts ON Threads.id = Posts.replyTo
GROUP BY Threads.id /* Technically you are supposed to list all columns here, but in MySQL it works fine to just list the primary key */
ORDER BY post_count

方法二:

SELECT *, (SELECT COUNT(*) FROM Posts WHERE Threads.id = Posts.replyTo) post_count
FROM Threads
ORDER BY post_count

注意:您的列名称不佳。您不应该将所有ID命名为相同,这使得连接表格变得更加困难。将replyTo更改为thread_id,将id主题更改为thread_id,然后发布到post_id