简体   繁体   中英

MySQL order by count subquery

I have an "Author" table, containing Authors(Nicknames & IDs).

In the Content table, each item has a field "Author" containing the ID of the author who made it.

I want to select all authors using a SELECT query, and to order them by them amount of Content they created .

This is what I tried so far :

SELECT id,Nickname FROM Authors 
WHERE 1 ORDER BY (SELECT COUNT(*) FROM Content WHERE Author=id) ASC

It runs, but the output is invalid - it has no specific order...

Any help is greatly appreciated.

You could use:

SELECT a.id,a.Nickname
FROM Authors  a
LEFT JOIN Content c
  ON c.Author=a.id
GROUP BY a.id,a.Nickname
ORDER BY COUNT(*) DESC

This should do what you want:

SELECT a.id, a.Nickname
FROM Authors a
WHERE 1
ORDER BY (SELECT COUNT(*) FROM Content c WHERE c.Author = a.id) ASC;

This makes the correlation explicit. Your version would produce unsorted results if Content had an id column -- which is likely.

More commonly, you would want the count in the SELECT , and you would do:

SELECT a.id, a.Nickname, COUNT(c.Author) as num_content
FROM Authors a LEFT JOIN
     Content c
     ON c.Author = a.id
GROUP BY a.id, a.Nickname
ORDER BY num_content ASC;

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