zoukankan      html  css  js  c++  java
  • mysql中去重 distinct 用法

    distinct的使用语法是这样的:

    select distinct expression[,expression...] from tables [where conditions];


    在使用distinct的过程中主要注意一下几点:

    • 在对字段进行去重的时候,要保证distinct在所有字段的最前面
    • 如果distinct关键字后面有多个字段时,则会对多个字段进行组合去重,只有多个字段组合起来的值是相等的才会被去重

    下面我们通过在开发过程中经常遇到的一些关于distinct的实例来加深大家对该关键字用法的理解:

    数据库表结构和数据如下图所示:

    •  对单个字段进行去重sql:
    select distinct  age from user;
    
    查询结果
    age
    10
    20
    30
    • 对多个字段进行去重sql:
    select distinct name,age from user;
    
    查询结果
    name    age
    One    10
    Zero    20
    Two    20
    Four    30
    One    30
    • 对多个字段进行去重并求count的sql(实际中我们往往用distinct来返回不重复字段的条数(count(distinct id)),其原因是distinct只能返回他的目标字段,而无法返回其他字段):
    select count(distinct name,age) as total from user;
    
    查询结果
    total
    5
    • 对select * 进行去重
    select distinct * from user;
    
    由于 * 代表所有字段,所以该sql和 select distinct id,name,age,sign from user 语义相同
    
    查询结果:
    id        name    age        sign
    1        One        10        梦想要有的,万一实现了呢
    2        Zero    20        http://www.chaoshizhushou.com
    3        Two        20        OneZeroTwoFour
    4        Four    30        加油
    5        One        30        学习才是硬道理
    6        Four    30        一日三省吾身

    如果sql这样写:select id,distinct name from user,这样mysql会报错,因为distinct必须放在要查询字段的开头。

    所以一般distinct用来查询不重复记录的条数。

    如果要查询不重复的记录,有时候可以用group by :

    select id,name from user group by name;

  • 相关阅读:
    Java数据库操作学习
    c3p0配置
    CachedRowSet 接口
    Android Library的依赖方式及发布(转)
    网站测试
    MySQL Server逻辑架构
    Service生命周期
    Activity的生命周期
    Android应用框架中的四个核心要点
    Android 最新架构
  • 原文地址:https://www.cnblogs.com/clubs/p/12594159.html
Copyright © 2011-2022 走看看