欢迎投稿

今日深度:

MySQL关键字Distinct的详细介绍,mysql关键字distinc

MySQL关键字Distinct的详细介绍,mysql关键字distinct


MySQL关键字Distinct用法介绍

DDL

Prepare SQL:

create table test(id bigint not null primary key auto_increment,
   name varchar(10) not null,
   phone varchar(10) not null,
   email varchar(30) not null)engine=innodb;

Prepare Data:

 insert into test(name, phone, email)values('alibaba','0517','alibaba@alibaba.com');
  insert into test(name, phone, email)values('alibaba','0517','alibaba@alibaba.com');
  insert into test(name, phone, email)values('baidu','010','baidu@baidu.com');
  insert into test(name, phone, email)values('tencent','0755','tencent@tencent.com');
  insert into test(name, phone, email)values('vipshop','020','vipshop@vipshop.com');
  insert into test(name, phone, email)values('ctrip','021','ctrip@ctrip.com');
  insert into test(name, phone, email)values('suning','025','suning@suning.com');

查询数据如下图所示:

鏌ヨ鎻掑叆鐨勬暟鎹? title=

第一种情况,使用Distinct关键字,查询单列数据,如下图所示:

浣跨敤鍏抽敭瀛楀崟鍒楁煡璇? title=

结果:对 name 字段进行去重处理,符合预期期望,确实筛选掉了重复的字段值alibaba;

第二种情况,使用Distinct关键字(在前),查询多列数据,如下图所示:

浣跨敤鍏抽敭瀛楀鍒楁煡璇? title=

结果:对 name 字段进行去重处理,结果不符合预期期望,没有筛选掉重复的字段值alibaba;

第二种情况,使用Distinct关键字(在后),查询多列数据,如下图所示:

浣跨敤鍏抽敭瀛楀鍒楁煡璇? title=

结果:对 name 字段进行去重处理,结果不符合预期期望,抛出SQL异常,错误码:1064;

解决办法:

不要用子查询,用分组来解决:

瑙e喅鏂瑰紡

总结: SQL查询能用一条语句解决的尽量不要增加SQL的复杂度,特别是子查询!!!

以上就是关于MySQL关键字Distinct用法的讲解,如有疑问,请留言或者到本站设讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

www.htsjk.Com true http://www.htsjk.com/Mysql/16139.html NewsArticle MySQL关键字Distinct的详细介绍,mysql关键字distinct MySQL关键字Distinct用法介绍 DDL Prepare SQL: create table test(id bigint not null primary key auto_increment, name varchar(10) not null, phone varchar(10) not null, ema...
评论暂时关闭