有时候数据库中表的数据可能存在重复的情况,如何从表中找出重复的数据呢?本文中提到两种方式:
使用group by + 临时表
使用group by + having
需求
根据价格price找出相同数据的行记录。可以见到下面的数据中name中的值会出现相同的记录,需要将它们找出来。
![7e7b8b000d2e5e62fdd7fdb2442b99ce.png](https://img-blog.csdnimg.cn/img_convert/7e7b8b000d2e5e62fdd7fdb2442b99ce.png)
方式1-临时表实现
- 先统计每个price出现的次数,次数大于1则肯定是重复的
![0950c1f6d4e73527a8f79e5a895087a6.png](https://img-blog.csdnimg.cn/img_convert/0950c1f6d4e73527a8f79e5a895087a6.png)
- 将上面的结果看做是一个临时表,从临时表中直接取出重复的行记录
![c278f84dcc1d243f017c0b2cf0316488.png](https://img-blog.csdnimg.cn/img_convert/c278f84dcc1d243f017c0b2cf0316488.png)
从原始数据中看出来只有价格50和100具有重复值
方式2-使用having
mysql> select price,count(*)
-> from products
-> group by price
-> having count(*) > 1; -- 直接指定条件
![2d4312d525e39fdf0b381648c3ca7d84.png](https://img-blog.csdnimg.cn/img_convert/2d4312d525e39fdf0b381648c3ca7d84.png)
重复出现n次的数据
mysql> select price, count(*)
-> from products
-> group by price
-> having count(*) > n; -- 直接指定条件
需求-提取重复行的全部数据
select p.id, p.price, p.name
from products p
join (select price, count(*) as number
from products
group by price
having count(*) > 1) as temp -- 将临时表的price 和 原始表的price进行联结,查询原始表的全部数据
on p.price=temp.price;
![35bd3d9a563073ed694673a46c9973e2.png](https://img-blog.csdnimg.cn/img_convert/35bd3d9a563073ed694673a46c9973e2.png)
SQL语句执行顺序
- select
- from
- where
- group by
- having
- order by(desc是降序)