2013-05-05 62 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