我们在日常使用的时候,可能是需要去除重复数据的情况,那么使用 distinct 刚好满足需求

image.png
所有数据

去除重复的 intaketime 入学日期

  1. select distinct intaketime from student;

image.png
去除掉所有 intaketime 字段重复的记录-图

去除掉 name和intaketime都相同的记录

select distinct name, intaketime from student;

image.png

那我们看到 里面的 “李欣” 为什么还有重复, 因为我们上的这个语句,是要求 name 和intaketime都相同,才可以, 这2个李欣的 intaketime不同,就不是重复的

select name, distinct intaketime from person;

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 intaketime from person' at line 1

报错了。 因为distinct 前面不能出现任何其他的字段。

示例2: 统计公司一共有多少个不同的岗位
分析: 统计 — 使用count
不同的工作岗位 distinct 对岗位去重

select count(distinct depId) as 'count' from person;

image.png

总结:

  1. distinct 可以联合多个字符,符合要求的去除重复数据 distinct name, intaketime
  2. distinct 前面不能有任何其他的字段
  3. distinct 只是返回显示结果,并不会对源数据产生任何影响,也没有修改 源数据, select 语句是不会修改源数据的