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

这给了我以下结果 - 正如我根据表中的数据所需要的那样:

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

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

4

2 回答 2

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() = (您的查询返回的最大值)。

于 2013-05-05T15:18:16.283 回答
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
于 2013-05-05T14:58:09.873 回答