2013-05-05 84 views
0

我有以下查詢:SQL max函數

SELECT q.category_id as Category_id , COUNT(q.question_id) as count 
from questions as q 
    INNER JOIN interestingQuestion as i using (question_id) 
group by q.category_id 

這是給我下面的結果 - 就像我需要根據我在我的表中的數據:

Category_id Count 

    5   1 
    6   3 

現在我需要找到具有最高計數器CATEGORY_ID,所以我做了以下查詢:

SELECT t.Category_id, MAX(t.Count) 
from(
    SELECT q.category_id as Category_id , COUNT(q.question_id) as count 
    from questions as q INNER JOIN interestingQuestion as i using (question_id) 
    group by q.category_id 
)as t 

和那我得到的結果是:

category_id MAX(t.count) 
    5    3 

這是一個混合起來的結果,它的發現最大計數器,但它給我一個錯誤的CATEGORY_ID

爲什麼會發生?我該如何解決它?

回答

1

您可以使用此:

SELECT 
    q.category_id as Category_id, 
    COUNT(q.question_id) as count 
FROM 
    questions as q INNER JOIN interestingQuestion as i 
    USING (question_id) 
GROUP BY q.category_id 
ORDER BY 
    COUNT(q.question_id) DESC 
LIMIT 1 

這將COUNT在遞減順序,只返回包含您需要的值的第一行訂購您的結果。

編輯

如果存在具有相同的最大值多個行,你可以使用這樣的事情:

SELECT 
    q.category_id as Category_id, 
    COUNT(q.question_id) as count 
FROM 
    questions as q INNER JOIN interestingQuestion as i 
    USING (question_id) 
GROUP BY 
    q.category_id 
HAVING 
    COUNT(q.question_id) = (SELECT MAX(t.Count) FROM (
    SELECT COUNT(q.question_id) as count 
    FROM 
     questions as q INNER JOIN interestingQuestion as i 
     USING (question_id) 
    GROUP BY 
     q.category_id) as t) 

我用你的查詢作爲子查詢來計算最大計數,並且我返回所有行HAVING COUNT()=(查詢返回的最大值)。

+0

Tnx!這是行之有效的,是否有可能通過這種方式返回一些結果(所有結果都與MAX相同)(不知道有多少結果)? – 2013-05-05 15:22:59

+0

@ShaiZarzewski我已經更新了我的答案,現在應該沒問題! – fthiella 2013-05-05 15:28:22

+1

太棒了!它的工作很好,只需在最後一行之前的最後一行添加「as」,以便它能夠工作 – 2013-05-05 15:41:04

0

這應該工作

SELECT q.category_id as Category_id , COUNT(q.question_id) as count 
from questions as q INNER JOIN interestingQuestion as i using (question_id) 
group by q.category_id HAVING max(count(q.question_id)) 

,但你可能需要做這種方式。

SELECT t.Category_id, t.Count 
from(
    SELECT q.category_id as Category_id , COUNT(q.question_id) as count 
    from questions as q INNER JOIN interestingQuestion as i using (question_id) 
    group by q.category_id 
)as t 
order by max(t.count) desc 
limit 1 
+0

我得到的第一個查詢:#1111 - 組函數的無效使用, 和第二個我得到:「#1064 - 你的SQL語法有錯誤;檢查相應的手冊到您的MySQL服務器版本的正確語法使用附近'1 t.Category_id,..「 和沒有」頂部1「我得到的值與行5-1 – 2013-05-05 15:02:15

+0

@ShaiZarzewski抱歉沒有注意到你在MySQL上。 'top 1'應該是'limit 1'而不是 – 2013-05-05 15:04:46

+0

我仍然得到與結果相同的行(5-1) – 2013-05-05 15:09:17