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

查询多个字段重复

......

相关推荐
Elastic 中国社区官方博客7 小时前
将你自己的密钥用于现有 Elastic Cloud 部署
大数据·数据库·elasticsearch·全文检索
红海云7 小时前
Jev:给智能系统做判断的模型
大数据·数据库·人工智能
wjkjpcba7 小时前
PCBA烧录程序是什么:PCBA包工包料厂家解析烧录与测试
linux·数据库·人工智能·smt贴片加工·pcba贴片加工厂
꯭自꯭闭꯭8 小时前
达梦事物特性及MVCC
linux·运维·数据库
小马同学-8 小时前
MySQL主从复制和读写分离
数据库·mysql
谢亮_vipxieliang8 小时前
Spring 事务失效的常见场景
java·开发语言·数据库·spring boot
海绵宝宝转agent8 小时前
MySql高频面试八股开源笔记总结
mysql·面试·开源
geovindu9 小时前
sql: JSON and XML Data Handling in SQL using sql server 2025
大数据·数据库·sqlserver·数据库开发·数据库架构
IT大白鼠9 小时前
图数据库系列 · 第 02 篇——架构拆解:原生图存储到因果集群
数据库·架构·nosql
余槐i10 小时前
数据没回滚也不报错:@Transactional 自调用失效的 3 种复现与修复
spring boot·mysql·多线程·spring 事务