2016-07-21 170 views
0

我正在研究一個匹配用戶和組的興趣的函數。根據我的查詢結果,我能夠獲得匹配,但是我需要幫助根據group_id以降序對結果進行排序,結果最多。MySQL查詢結果集按大多數結果/匹配順序降序排列

例如,基於下面的結果集,我想這樣排序... 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) 

下面是示例結果集。

enter image description here

我很感謝您的幫助。謝謝。

+2

編輯你的問題,幷包括你正在使用的查詢來獲得結果。 –

+0

我編輯了這個問題,謝謝 – aabejero

回答

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 ... ===你的信號SQL,其中

+0

完美,你提供的第一個查詢是我需要的。該查詢也同時具有不同的功能。精彩。謝謝 – aabejero

+0

嗨SIDU,你能向我解釋一下「GROUP BY 1 ORDER BY 2 DESC」的含義嗎? :) – aabejero

+1

GROUP BY 1 ORDER BY 2 DESC ==是GROUP BY GROUP_ID的簡寫ORDER BY count(*)DESC – SIDU