使用DISTINCT查询basket_game_master表无法去重doctor_user_id怎么办
问题原因
你写的SQL里DISTINCT是对SELECT后所有字段的组合值进行去重,只要同一个doctor_user_id对应的score、time_in_seconds或者doctor_name有差异,就会被判定为不同行返回,完全达不到按doctor_user_id唯一去重的要求。
解决方案
方案1:适用于支持窗口函数的数据库(MySQL 8.0+、MariaDB 10.2+、PostgreSQL等)
用ROW_NUMBER()窗口函数按医生ID分组排序,取每组第一条即可:
SELECT doctor_user_id, doctor_name, score, time_in_seconds FROM ( SELECT doctor_user_id, doctor_name, score, time_in_seconds, -- 按医生ID分组,每组内按分数降序、耗时升序排序 ROW_NUMBER() OVER ( PARTITION BY doctor_user_id ORDER BY score DESC, time_in_seconds ASC ) AS row_num FROM basket_game_master WHERE game_id = ? ) AS temp WHERE row_num = 1 -- 取每个医生的最优记录 ORDER BY score DESC, time_in_seconds ASC LIMIT ?
方案2:适用于不支持窗口函数的低版本MySQL
用自关联过滤最优记录:
SELECT a.doctor_user_id, a.doctor_name, a.score, a.time_in_seconds FROM basket_game_master a LEFT JOIN basket_game_master b ON a.doctor_user_id = b.doctor_user_id AND a.game_id = b.game_id -- 找同医生同游戏下更优的记录:分数更高,或者分数相同耗时更短 AND (b.score > a.score OR (b.score = a.score AND b.time_in_seconds < a.time_in_seconds)) WHERE a.game_id = ? AND b.id IS NULL -- 不存在更优记录,当前就是最优 ORDER BY a.score DESC, a.time_in_seconds ASC LIMIT ?
注意事项
请使用预编译语句传入game_id和limit参数,不要直接拼接SQL字符串,避免SQL注入风险。
内容的提问来源于stack exchange,提问作者Vinod Sutar
相关产品推荐
相关产品推荐

