創(chuàng)建測試表和數(shù)據(jù)
# 創(chuàng)建表
create table if not exists t_duplicate (
name varchar(255) not null,
age int not null
);
# 插入測試數(shù)據(jù)
insert into t_duplicate(name, age) values('a', 1);
insert into t_duplicate(name, age) values('a', 2);
查詢單個字段重復(fù)
使用 count() 函數(shù)、group by 分組和 having 分組后篩選
select name, count(*) count
from t_duplicate
group by name
having count > 1;
-
group by name
:根據(jù)name
字段分組。 -
count(*)
:計(jì)算每個分組的記錄數(shù)量。 -
having count > 1
:在分組后篩選分組的記錄數(shù) > 1 的分組。
查詢結(jié)果:
name | count |
---|---|
a | 2 |
使用子查詢和 in 函數(shù)
select *
from t_duplicate
where name in (
select name
from t_duplicate
group by name
having count(*) > 1
)
- 子查詢:根據(jù)
name
分組,篩選分組的記錄數(shù) > 1 的分組,即查詢重復(fù)的name
。 - 外部查詢:用
in
篩選name
重復(fù)的記錄。
查詢結(jié)果:
name | age |
---|---|
a | 1 |
a | 2 |
使用窗口函數(shù) over 和 partition by 分區(qū)
select `name`, count
from (
select name, (count(*) over (partition by name)) as count
from t_duplicate
) t
where count > 1
-
partition by name
:按照name
字段分區(qū),相同的name
值在一個分區(qū)。 -
count(*) over
:計(jì)算每個分區(qū)的記錄數(shù)。 -
count > 1
:篩選分區(qū)記錄數(shù) > 1 的數(shù)據(jù)。
查詢結(jié)果:文章來源:http://www.zghlxwxcb.cn/news/detail-706289.html
name | count |
---|---|
a | 2 |
a | 2 |
查詢多個字段重復(fù)
……文章來源地址http://www.zghlxwxcb.cn/news/detail-706289.html
到了這里,關(guān)于MySQL/MariaDB 查詢某個 / 多個字段重復(fù)數(shù)據(jù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!