count(distinct) 去重
distinct 关键字用于去重,与 count() 搭配,用于去重统计行数:
select count(distinct sid) from t_student_mt3
语句优化
count(distinct) 会使用 uniqExact() 精确去重
查看语句优化:
explain syntax select count(distinct sid) from t_student_mt3
执行结果:
SELECT uniqExact(sid)
FROM t_student_mt3
uniqCombined
使用 uniqCombined() 替代 distinct,性能可提升 10倍以上
应用场景
千万级以上的数据,建议不要使用 distinct 去重查询,改为近似去重 uniqCombined()
能接受 2% 左右的 数据误差,可直接使用这种去重方式提升查询性能。
原理
uniqCombined() 底层采用类似 HyperLogLog 算法实现
例子
select uniqCombined(sid) from t_student_mt3;
参考:https://blog.csdn.net/qq_40378034/article/details/120473116