带有额外数据的sql max函数

时间:2013-05-05 14:54:16

标签: mysql sql sql-function

我有以下查询:

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

为什么会这样?我该如何解决呢?

2 个答案:

答案 0 :(得分: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()=(查询返回的最大值)。

答案 1 :(得分: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