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

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 に答える