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

查询多个字段重复

......

相关推荐
技术宝哥18 分钟前
Redis(2):Redis + Lua为什么可以实现原子性
数据库·redis·lua
学地理的小胖砸2 小时前
【Python 操作 MySQL 数据库】
数据库·python·mysql
不知几秋2 小时前
sqlilab-Less-18
sql
dddaidai1232 小时前
Redis解析
数据库·redis·缓存
数据库幼崽2 小时前
MySQL 8.0 OCP 1Z0-908 121-130题
数据库·mysql·ocp
Amctwd2 小时前
【SQL】如何在 SQL 中统计结构化字符串的特征频率
数据库·sql
betazhou3 小时前
基于Linux环境实现Oracle goldengate远程抽取MySQL同步数据到MySQL
linux·数据库·mysql·oracle·ogg
lyrhhhhhhhh3 小时前
Spring 框架 JDBC 模板技术详解
java·数据库·spring
喝醉的小喵5 小时前
【mysql】并发 Insert 的死锁问题 第二弹
数据库·后端·mysql·死锁
付出不多5 小时前
Linux——mysql主从复制与读写分离
数据库·mysql