MySQL/MariaDB 查询某个 / 多个字段重复数据

创建测试表和数据

sql 复制代码
# 创建表
create table if not exists t_duplicate (
  name varchar(255) not null,
  age int not null
);

# 插入测试数据
insert into t_duplicate(name, age) values('a', 1);
insert into t_duplicate(name, age) values('a', 2);

查询单个字段重复

使用 count() 函数、group by 分组和 having 分组后筛选

sql 复制代码
select name, count(*) count
from t_duplicate
group by name
having count > 1;
  • group by name:根据 name 字段分组。
  • count(*):计算每个分组的记录数量。
  • having count > 1:在分组后筛选分组的记录数 > 1 的分组。

查询结果:

name count
a 2

使用子查询和 in 函数

sql 复制代码
select *
from t_duplicate
where name in (
  select name
  from t_duplicate
  group by name
  having count(*) > 1
)
  • 子查询:根据 name 分组,筛选分组的记录数 > 1 的分组,即查询重复的 name
  • 外部查询:用 in 筛选 name 重复的记录。

查询结果:

name age
a 1
a 2

使用窗口函数 over 和 partition by 分区

sql 复制代码
select `name`, count
from (
  select name, (count(*) over (partition by name)) as count
  from t_duplicate
) t
where count > 1
  • partition by name:按照 name 字段分区,相同的 name 值在一个分区。
  • count(*) over:计算每个分区的记录数。
  • count > 1:筛选分区记录数 > 1 的数据。

查询结果:

name count
a 2
a 2

查询多个字段重复

......

相关推荐
q***48251 小时前
mysql用户名怎么看
数据库·mysql
夏日玲子1 小时前
【Redis】Redis常用命令合集
数据库·redis·缓存
r***12381 小时前
若依微服务中配置 MySQL + DM 多数据源
android·mysql·微服务
万邦科技Lafite1 小时前
1688图片搜索商品API接口(item_search_img)使用指南
java·前端·数据库·开放api·电商开放平台
自在极意功。1 小时前
SQL查询语句深度解析:从基础到进阶,写出高效优雅的SQL!
数据库·sql
north_eagle1 小时前
MySQL 业务数据,报表方案
大数据·数据库
ALex_zry2 小时前
MySQL连接数管理与优化实操经验分享
android·mysql·adb
r***12382 小时前
Spring boot启动原理及相关组件
数据库·spring boot·后端
数据库学啊2 小时前
大数据场景下时序数据库选型指南:TDengine为什么凭借领先的技术和实践脱颖而出?
大数据·数据库·时序数据库·tdengine
t***D2642 小时前
MySQL安全
数据库·mysql·安全