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

查询多个字段重复

......

相关推荐
川石课堂软件测试3 小时前
MySQL数据库之DBA命令
数据库·网络协议·mysql·http·单元测试·prometheus·dba
ybb_ymm4 小时前
mysql8在linux下的默认规则修改
linux·运维·数据库·mysql
倔强的石头_5 小时前
Navicat Premium 与金仓数据库融合实践:高效管理国产数据库新方案
数据库
程序新视界6 小时前
为什么要尽量将MySQL表字段要设置为NOT NULL?
数据库·mysql·dba
怪兽20146 小时前
SQL优化手段有哪些
java·数据库·面试
lypzcgf7 小时前
FastbuildAI后端数据库模块注册分析
数据库·ai应用·ai创业·智能体平台·ai应用平台·agent平台·fastbuildai
xyy20258 小时前
Spring事务的传播方式
java·数据库·spring
非凡的世界8 小时前
Thinkphp8 Redis队列与消息队列topthink/think-queue 原创
数据库·redis·bootstrap·thinkphp
yookay zhang8 小时前
DM线程的管理知识学习
数据库