2011-05-23 54 views
0

我的表如下所示:MySQL查詢找到最流行的入門

hook_bait | brand | flavour 
---------------------------------- 
corn  |   | 
bread  |   | 
boily  | variable | variable 

我需要運行一個MySQL查詢,這將使我最流行的hook_bait的名稱,如果一個boily - 什麼牌子和口味最流行的boily是。

我不知道從哪裏開始

+6

你怎麼算普及? – 2011-05-23 13:40:11

+2

您需要受歡迎的scorint機制。它是如何衡量的? – Alp 2011-05-23 13:41:11

+2

該表中沒有任何內容可以告訴你流行程度,數字在哪裏? – Roger 2011-05-23 13:41:48

回答

4

您可以通過查詢得到最流行的hook_bait這樣的:

SELECT 
    hook_bait, 
    COUNT(hook_bait) AS popularity 
FROM sample_table 
GROUP BY hook_bait 
ORDER BY popularity DESC 
LIMIT 0, 1 

完整的示例查詢:

SELECT 
    hook_bait, 
    IF(hook_bait = 'boily', (SELECT brand FROM sample_table t2 WHERE t2.hook_bait = t1.hook_bait GROUP BY brand ORDER BY COUNT(brand) DESC LIMIT 1), '-') AS brand, 
    IF(hook_bait = 'boily', (SELECT flavour FROM sample_table t2 WHERE t2.hook_bait = t1.hook_bait GROUP BY flavour ORDER BY COUNT(flavour) DESC LIMIT 1), '-') AS flavour 
FROM sample_table t1 
GROUP BY hook_bait 
ORDER BY COUNT(hook_bait) DESC 
LIMIT 0, 1 
+1

評論後23秒,好! :D – Jacob 2011-05-23 13:45:29

+0

那是快速 - 感謝您的幫助 – jeff 2011-05-23 14:10:05

+0

好一個哥們,我希望這也能幫助別人! – 2014-01-14 22:27:19