mysql結(jié)果與預(yù)期不符:找出答案被復(fù)制次數(shù)最多的
在一個(gè)問答系統(tǒng)中,我們需要找出每個(gè)問題下被復(fù)制次數(shù)最多的答案。原始查詢?nèi)缦拢?/p>
select question_id, answer_id, max(copy_count) as max_copy_count from answer_copy_count group by question_id;
然而,查詢結(jié)果令人困惑,因?yàn)槟承┐鸢傅?answer_id 明顯不正確。
為了解決這個(gè)問題,我們需要考慮修改查詢以在 group by 子句中包含額外的列。但這樣做卻并不能解決問題。
這里我們介紹一個(gè)不同的解決方案,適用于 mysql 8.0 及更高版本:使用窗口函數(shù)。
窗口函數(shù)
窗口函數(shù)可以在查詢結(jié)果中對指定行或組進(jìn)行計(jì)算。在本例中,我們可以使用 row_number() 函數(shù)或 rank() 函數(shù)來對每個(gè)問題下復(fù)制次數(shù)相同的所有答案進(jìn)行計(jì)數(shù),然后只選擇排名第一的答案。
使用 row_number() 函數(shù)
row_number() 函數(shù)按指定順序生成行編號(hào),在此情況下按復(fù)制次數(shù)降序排序。
select * from ( select question_id, answer_id, copy_count, row_number() over (partition by question_id order by copy_count desc) as idx from answer_copy_count ) t where idx = 1;
此查詢將僅返回每個(gè)問題下復(fù)制次數(shù)最多的答案。
使用 rank() 函數(shù)
rank() 函數(shù)類似于 row_number() 函數(shù),但它會(huì)為復(fù)制次數(shù)相同的答案分配相同的排名。
SELECT * FROM ( SELECT question_id, answer_id, copy_count, rank() OVER (PARTITION BY question_id ORDER BY copy_count DESC) AS idx FROM answer_copy_count ) t WHERE idx = 1;
此查詢將返回每個(gè)問題下復(fù)制次數(shù)相同的答案。