简体   繁体   中英

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. 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 ?

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 .

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:

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.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM