zoukankan      html  css  js  c++  java
  • 去重是distinct还是group by?

    distinct简单来说就是用来去重的,而group by的设计目的则是用来聚合统计的,两者在能够实现的功能上有些相同之处,但应该仔细区分,因为用错场景的话,效率相差可以倍计。

    单纯的去重操作使用distinct,速度是快于group by的

    distinct

    distinct支持单列、多列的去重方式。 
    单列去重的方式简明易懂,即相同值只保留1个。 
    多列的去重则是根据指定的去重的列信息来进行,即只有所有指定的列信息都相同,才会被认为是重复的信息。

    干巴巴的说不好理解,示例一下:

    示例数据表中的数据:
    mysql> select * from talk_test;
    +----+-------+--------+
    | id | name  | mobile |
    +----+-------+--------+
    |  1 | xiao9 | 555555 |
    |  2 | xiao6 | 666666 |
    |  3 | xiao9 | 888888 |
    |  4 | xiao9 | 555555 |
    |  5 | xiao6 | 777777 |
    +----+-------+--------+
    
    
    进行单列去重后的结果:
    
    mysql> select distinct(name) from talk_test;
    +-------+
    | name  |
    +-------+
    | xiao9 |
    | xiao6 |
    +-------+
    2 rows in set (0.01 sec)
    
    mysql> select distinct(mobile) from talk_test;
    +--------+
    | mobile |
    +--------+
    | 555555 |
    | 666666 |
    | 888888 |
    | 777777 |
    +--------+
    **只会保留指定的列的信息
    
    进行多列去重后的结果:
    mysql> select distinct name,mobile from talk_test;
    +-------+--------+
    | name  | mobile |
    +-------+--------+
    | xiao9 | 555555 |
    | xiao6 | 666666 |
    | xiao9 | 888888 |
    | xiao6 | 777777 |
    +-------+--------+
    **只有所有指定的列信息都相同,才会被认定为重复的信息

    group by使用的频率相对较高,但正如其功能一样,它的目的是用来进行聚合统计的,虽然也可能实现去重的功能,但这并不是它的长项。

  • 相关阅读:
    九度oj 题目1051:数字阶梯求和
    九度oj 题目1472:求两个多项式的和
    九度oj 题目1173:查找
    九度oj 题目1447:最短路
    九度oj 题目1104:整除问题
    [Luogu] 维护序列
    [Luogu] 计算系数
    [Luogu] 聪明的质监员
    [Luogu] Mayan游戏
    [Luogu] 选择客栈
  • 原文地址:https://www.cnblogs.com/shamo89/p/8944543.html
Copyright © 2011-2022 走看看