简体   繁体   中英

MYSQL order rows by most appearing value in other table

I am working on a basic social network using PHP and MYSQL. I am trying to show the 4 most popular posts in a table.

I have two tables, table 1 is 'discussions' and table 2 is 'comments' . The table 'discussions' has a column ' id ', which matches the column 'discid' in the table 'comments' . So whenever a user comments on a discussion, a row is added to the table 'comments' with 'discid' being the id of the discussion. I can show the most recent comments and discussions, but I can't get it to show the most popular discussions, so the discussions with the most comments.

So I need to find a way to sort my tables discussions by the number of times a certain discussion id appears in the column 'discid' of the table 'comments' .

For ex.:

 On the discussion with id 7, there are 4 comments with discid 1.
 On the discussion with id 2, there are 3 comments with discid 2.

So I need my sql query to show first id 7 and then id 2,...

Anyone who can help me with this? Would be greatly appreciated!

Let me know if it works or..

SELECT d.*
FROM discussions AS d
JOIN ( SELECT c.*, COUNT(c.discid) AS cnt
       FROM comments AS c
       GROUP BY c.discid
     ) AS c2 ON ( c2.discid = d.id )
ORDER BY c2.cnt DESC;
   SELECT discid AS Discussion_ID, COUNT(*) AS occurences
    FROM comments
    GROUP BY discid
    ORDER BY occurences DESC
    LIMIT 4

Hope this helps.

I would try something like

SELECT discid,COUNT(*) AS cnt FROM comments GROUP BY discid ORDER BY cnt DESC LIMIT 5;

This will present you a list of discid-s and the count of comments called 'cnt', order them descending by the count.

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