Fork me on GitHub

SQL进阶-4-查找重复行数据

SQL进阶-4-如何查找重复行数据

有时候数据库中表的数据可能存在重复的情况,如何从表中找出重复的数据呢?本文中提到两种方式:

  • 使用group by + 临时表

  • 使用group by + having

需求

根据价格price找出相同数据的行记录

方式1-临时表实现

  1. 先统计每个price出现的次数,次数大于1则肯定是重复的

  1. 将上面的结果看做是一个临时表,从临时表中直接取出重复的行记录

从原始数据中看出来只有价格50和100具有重复值

方式2-使用having

1
2
3
4
mysql> select price,count(*)
-> from products
-> group by price
-> having count(*) > 1; -- 直接指定条件

重复出现n次的数据

1
2
3
4
mysql> select price, count(*)
-> from products
-> group by price
-> having count(*) > n; -- 直接指定条件

需求-提取重复行的全部数据

1
2
3
4
5
6
7
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;

SQL语句执行顺序

  1. select
  2. from
  3. where
  4. group by
  5. having
  6. order by(desc是降序)

本文标题:SQL进阶-4-查找重复行数据

发布时间:2020年08月30日 - 23:08

原始链接:http://www.renpeter.cn/2020/08/30/SQL%E8%BF%9B%E9%98%B6-4-%E6%9F%A5%E6%89%BE%E9%87%8D%E5%A4%8D%E8%A1%8C%E6%95%B0%E6%8D%AE.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

Coffee or Tea