DQL语句-distinct去重

MySQL | DQL语句-distinct去重


🪄个人博客https://vite.xingji.fun

查询工作岗位

sql 复制代码
select job from emp;
sql 复制代码
mysql> select job from emp;

+-----------+
| job       |
+-----------+
| CLERK     |
| SALESMAN  |
| SALESMAN  |
| MANAGER   |
| SALESMAN  |
| MANAGER   |
| MANAGER   |
| ANALYST   |
| PRESIDENT |
| SALESMAN  |
| CLERK     |
| CLERK     |
| ANALYST   |
| CLERK     |
+-----------+
14 rows in set (0.00 sec)

可以看到工作岗位中有重复的记录,如何在显示的时候去除重复记录呢?在字段前添加distinct关键字

sql 复制代码
select distinct job from emp;
sql 复制代码
mysql> select distinct job from emp; 

+-----------+
| job       |
+-----------+
| CLERK     |
| SALESMAN  |
| MANAGER   |
| ANALYST   |
| PRESIDENT |
+-----------+
5 rows in set (0.00 sec)

注意:这个去重只是将显示的结果去重原表数据不会被更改。

接下来测试一下,在distinct关键字前添加其它字段是否可以?

sql 复制代码
select ename, distinct job from emp;

分析一下:ename是14条记录distinct job是5条记录,可以同时显示吗?

sql 复制代码
mysql> select ename, distinct job from emp;

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'distinct job from emp' at line 1 

报错了,通过测试得知,distinct只能出现在所有字段的最前面
当distinct出现后,后面多个字段一定是联合去重,我们来做两个练习就知道了:
练习1:找出公司中所有的工作岗位

sql 复制代码
select distinct job from emp;
sql 复制代码
mysql> select distinct job from emp;

+-----------+
| job       |
+-----------+
| CLERK     |
| SALESMAN  |
| MANAGER   |
| ANALYST   |
| PRESIDENT |
+-----------+
5 rows in set (0.00 sec)

练习2:找出公司中不同部门的不同工作岗位

sql 复制代码
select distinct deptno,job from emp;
sql 复制代码
mysql> select distinct deptno,job from emp;

+--------+-----------+
| deptno | job       |
+--------+-----------+
|     20 | CLERK     |
|     30 | SALESMAN  |
|     20 | MANAGER   |
|     30 | MANAGER   |
|     10 | MANAGER   |
|     20 | ANALYST   |
|     10 | PRESIDENT |
|     30 | CLERK     |
|     10 | CLERK     |
+--------+-----------+
9 rows in set (0.00 sec)
相关推荐
笨手笨脚の几秒前
Mysql 的锁机制
数据库·mysql··死锁·间隙锁
老友@7 分钟前
一次由 PageHelper 分页污染引发的 Bug 排查实录
java·数据库·bug·mybatis·pagehelper·分页污染
hzk的学习笔记29 分钟前
Redisson解锁失败,watchdog会不会一直续期下去?
数据库·redis·缓存
合作小小程序员小小店44 分钟前
web网页开发,在线%商城,电商,商品购买%系统demo,基于vscode,apache,html,css,jquery,php,mysql数据库
开发语言·前端·数据库·mysql·html·php·电商
TDengine (老段)1 小时前
TDengine 字符串函数 CONCAT 用户手册
java·数据库·tdengine
一 乐1 小时前
旅游|内蒙古景点旅游|基于Springboot+Vue的内蒙古景点旅游管理系统设计与实现(源码+数据库+文档)
开发语言·前端·数据库·vue.js·spring boot·后端·旅游
星光一影1 小时前
基于SpringBoot智慧社区系统/乡村振兴系统/大数据与人工智能平台
大数据·spring boot·后端·mysql·elasticsearch·vue
bing.shao1 小时前
如何降低redis哈希值冲突概率
数据库·redis·哈希算法
ckm紫韵1 小时前
redis查询速度快的原因?
数据库·redis·缓存
yookay zhang2 小时前
达梦数据复制软件DMDRS
数据库