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)
相关推荐
苹果酱056714 分钟前
【Azure Redis 缓存】在Azure Redis中,如何限制只允许Azure App Service访问?
java·vue.js·spring boot·mysql·课程设计
枫叶200030 分钟前
OceanBase数据库-学习笔记1-概论
数据库·笔记·学习·oceanbase
仲夏plus40 分钟前
MySQL:慢SQL索引优化-使用explain/analyze进行耗时分析的方法
数据库
tcoding1 小时前
《MySQL 技术内幕-innoDB 存储引擎》笔记
数据库·笔记·mysql
L2ncE1 小时前
【LanTech】DeepWiki 101 —— 以后不用自己写README了
人工智能·程序员·github
Edward.W1 小时前
如何有效防止 SQL 注入攻击?
数据库·sql
我是哈哈hh1 小时前
【Git】初始Git及入门命令行
git·gitee·github·版本控制器
极小狐2 小时前
如何创建并使用极狐GitLab 部署令牌?
运维·git·ssh·gitlab·github
好想有猫猫2 小时前
【Redis】服务端高并发分布式结构演进之路
数据库·c++·redis·分布式·缓存
桥Dopey2 小时前
关系型数据库PostgreSQL for Mac 保姆级使用教程
数据库·postgresql