我可以按另一个表中的记录数对SQL查询结果进行排序吗?

时间:2011-01-31 17:44:16

标签: php sql database sqlite

这样的事情:

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

我正在使用SQLite,但任何示例都应该有所帮助。

1 个答案:

答案 0 :(得分:4)

在MySQL中,这可行:

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

在SQLite中,您可能需要添加一个额外的图层:

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