开发者

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜