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)
相关推荐
YuePeng42 分钟前
写了五年注解的低代码框架,2.0 决定让你连注解都不用写了
github·产品
小白ai1 小时前
从"能 ping 通吗"到"为什么上不了网"——我写了一个网络故障诊断引擎
github
徐小夕3 小时前
jitword 协同文档3.2发布:打造浏览器中最强word编辑器
前端·架构·github
齐翊5 小时前
分享一个在 Claude Code 里 [同时] 用多个 ApiKey 的方法
程序员·github·agent
A_Lonely_Cat5 小时前
记一次 GitHub 幽灵协作者大清洗:强制重写 Git 历史与穿透 CDN 缓存实践
git·github
极光技术熊1 天前
Spring AI 从入门到精通:构建你的 AI 开发知识体系
后端·github
用户39483951075531 天前
怎么让我的 Agent 真正"懂"我?——关于记忆、经验学习与预测的一些真实体验
github
jiayou641 天前
KingbaseES 表级与列级加密完全指南
数据库·后端
远航_1 天前
git submodule
前端·后端·github
fthux1 天前
如果你用 Mac,那你可能需要 Noti Shift
macos·开源·github