[英]Sort a MySQL result based on total count of another result
I have tables tbl_posts
and tbl_comments
with primary keys post_id
and comment_id
respectively. 我有表tbl_posts
和tbl_comments
,主键分别为post_id
和comment_id
。 I tried this code: 我试过这段代码:
$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
");
but I have no clue what it does. 但我不知道它的作用。 How do I combine two tables so that the total comments determines the order of the listed posts from tbl_posts
? 如何组合两个表,以便总评论确定tbl_posts
列出的帖子的tbl_posts
?
Try this, it's more readable if you separate per lines and work with joins 试试这个,如果你将每行分开并使用连接,它会更具可读性
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
It looks like you have tables named tbl_comment and tbl_post but your query has them listed as just comment and post . 看起来您有名为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");
This just fixes the query so it runs, and does not address any content issues you may have, namely the group by on both (what I am guessing) are primary keys. 这只是修复了查询以便它运行,并且没有解决您可能遇到的任何内容问题,即两者(我猜的是)的主要组是主键。
** EDIT ** To fix the sorting try: **编辑**要修复排序尝试:
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(*)
Explanation of your SQL: SQL的解释:
You are selecting column comment_id from table comments , column post_id from table post using a inner join, grouping by comment_id , post_id , with a limit of 10 results. 您正在从表注释中选择列comment_id ,使用内部联接从表发布中选择post_id列,通过comment_id , post_id进行分组,限制为10个结果。
I would try: 我会尝试:
$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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.