根据另一个结果的总计数对MySQL结果进行排序

时间:2012-06-25 16:26:32

标签: php mysql

我的表tbl_poststbl_comments分别包含主键post_idcomment_id。我试过这段代码:

$allPosts=mysql_query("
    select c.comment_id, post_id, count(*)
    from post u,
    comments c
    where u.comment_id = c.comment_id
    group by comment_id, post_id
    LIMIT 10
");

但我不知道它的作用。如何组合两个表,以便总评论确定tbl_posts列出的帖子的顺序?

3 个答案:

答案 0 :(得分:1)

试试这个,如果你将每行分开并使用联接

,它会更具可读性
select c.comment_id, post_id, count(*) 
from post u join comments c 
on u.comment_id = c.comment_id 
group by comment_id, post_id LIMIT 10

答案 1 :(得分:1)

看起来您有名为 tbl_comment tbl_post 的表格,但您的查询会将其列为评论并发布

select c.comment_id, post_id, count(*) 
from tbl_post u, tbl_comments c 
where u.comment_id = c.comment_id 
group by comment_id, post_id LIMIT 10


$allPosts=mysql_query("select c.comment_id, post_id, count(*) from tbl_post u, tbl_comments c where u.comment_id = c.comment_id group by comment_id, post_id LIMIT 10");

这只是修复了查询以便它运行,并且没有解决您可能遇到的任何内容问题,即两者上的分组(我猜的是主键)。

**编辑** 要修复排序,请尝试:

SELECT tbl_post.comment_id, count(*)  
FROM tbl_post, tbl_comments
WHERE tbl_post.comment_id = tbl_comment.comment_id  
GROUP BY comment_id LIMIT 10
ORDER BY count(*) 

答案 2 :(得分:0)

SQL的解释:

您正在使用内部联接从表帖子中的表评论,列 post_id 中选择 comment_id 列,按 comment_id post_id 进行分组,限制为10个结果。

我会尝试:

$allPosts = mysql_query("SELECT * FROM 
(SELECT c.comment_id, u.post_id, COUNT(*) AS 'count' FROM post u 
LEFT JOIN comments c ON c.comment_id = u.comment_id 
GROUP BY c.comment_id, u.post_id)
ORDER BY count DESC LIMIT 10");