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

查询多个字段重复

......

相关推荐
秦老师Q11 分钟前
php入门教程(超详细,一篇就够了!!!)
开发语言·mysql·php·db
打工的小王20 分钟前
redis(四)搭建哨兵模式:一主二从三哨兵
数据库·redis·缓存
Anarkh_Lee41 分钟前
【小白也能实现智能问数智能体】使用开源的universal-db-mcp在coze中实现问数 AskDB智能体
数据库·人工智能·ai·开源·ai编程
橘子131 小时前
MySQL用户管理(十三)
数据库·mysql
Dxy12393102161 小时前
MySQL如何加唯一索引
android·数据库·mysql
我真的是大笨蛋1 小时前
深度解析InnoDB如何保障Buffer与磁盘数据一致性
java·数据库·sql·mysql·性能优化
怣501 小时前
MySQL数据检索入门:从零开始学SELECT查询
数据库·mysql
shengli7221 小时前
机器学习与人工智能
jvm·数据库·python
2301_765703141 小时前
Python迭代器(Iterator)揭秘:for循环背后的故事
jvm·数据库·python
倔强的石头1061 小时前
关键信息基础设施的数据库选型:高可用、全链路安全与平滑替代的技术实践
数据库·安全·金仓数据库