【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 【查询字段】,必须放在要查询字段的开头,即放在第一个参数

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的时候没考虑后续记录的差异,学到了学到了~



#MySQL#
全部评论

相关推荐

点赞 评论 收藏
分享
缒梦&独舞:这家公司是这样的,去年给我实习offer了,不过也是面着玩儿的,他周六还要去做公益志愿活动
点赞 评论 收藏
分享
评论
5
5
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务