【SQL学习】distinct用法
系统学习SQL才发现自己对distinct的理解偏差还挺大的,稍微记录一下distinct的详细用法。
distinct——用来查询不重复记录的条数,即用distinct来返回不重复字段的条数
考虑如下product表:
product_id product_name number
001 food 100
002 clothes 50
003 furniture 10
001 food 500
004 book 1000
ATTENTION:
distinct 【查询字段】,必须放在要查询字段的开头,即放在第一个参数
distinct 【查询字段】,必须放在要查询字段的开头,即放在第一个参数
1. 单列distinct
coding——select distinct product_id from product
output:
product_id
001
002
003
004
可以发现重复的001编号被删去
2. 多列distinct
coding——select distinct product_id, product_name, number from product
output:
product_id product_name number
001 food 100
002 clothes 50
003 furniture 10
001 food 500
004 book 1000
会发现001编号的两个物品没有按我们预想的方式合一。因为多列的去重并不能去指定列,而是会将其视作一个整体进行去重。选取多个字段拼接的一条记录,不重复的所有记录。
3. 改进2中多列
使用group by
coding——select product_id, product_name, number from product group by product_id
output:
product_id product_name number
001 food 100
002 clothes 50
003 furniture 10
004 book 1000
会发现001按照我们想要状态进行了去重
总算明白自己刷SQL题的时候为什么有些地方数量总是对不上,原来是用distinct的时候没考虑后续记录的差异,学到了学到了~