我正在开发一个与用户和群组的兴趣相匹配的功能。根据我的查询结果,我能够获得匹配但是我需要帮助根据具有最多结果的group_id按降序对结果进行排序。
例如,根据下面的结果集,我想对它进行排序... group_id 47将位于顶部,因为它有4个结果,其次是group_id 44和group_id 48,结果为2,结果为1比如group_id的40,42,43和49将位于底部。
以下是示例查询。
SELECT * FROM `group_questionnaire_answers`
WHERE (question_id = 1 AND answer =3)
OR (question_id = 2 AND answer =1)
OR (question_id = 3 AND answer =4)
OR (question_id = 4 AND answer =4)
OR (question_id = 5 AND answer =4)
OR (question_id = 6 AND answer =3)
OR (question_id = 7 AND answer =3)
OR (question_id = 8 AND answer =4)
OR (question_id = 9 AND answer =5)
OR (question_id = 10 AND answer =2)
以下是样本结果集。
感谢您的帮助。感谢。
答案 0 :(得分:1)
这取决于你想要的方式:
SELECT group_id, count(*) AS num
FROM group_questionnaire_answers
WHERE ...
GROUP BY 1 ORDER BY 2 DESC
如果要显示所有详细信息,则需要使用自联接:
SELECT a.*
FROM group_questionnaire_answers AS a
JOIN (
SELECT group_id, count(*) AS num
FROM group_questionnaire_answers
WHERE ...
GROUP BY 1
) AS b ON a.group_id = b.group_id
WHERE ...
ORDER BY b.num DESC
WHERE ... ===你的orignal SQL where