简体   繁体   中英

Can I sort results of SQL query by the number of records in another table?

Something like this:

SELECT count(Answers.ID) as answertotal, Questions.* 
FROM Questions 
LEFT JOIN Answers ON Answers.qid=Questions.ID 
ORDER BY answertotal

I'm using SQLite, but any examples should help.

In MySQL, this would work:

SELECT count(Answers.ID) as answertotal, Questions.* 
FROM Questions 
LEFT JOIN Answers ON Answers.qid=Questions.ID 
GROUP BY Questions.ID
ORDER BY answertotal

In SQLLite, you may need to add an extra layer like this:

SELECT q.*, tots.answertotal
FROM Questions q
INNER JOIN ( 
  SELECT count(Answers.ID) as answertotal, Questions.ID as questionid
  FROM Questions 
  LEFT JOIN Answers ON Answers.qid=Questions.ID 
  GROUP BY Questions.ID
) tots ON tots.questionid = q.ID
ORDER BY tots.answertotal

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