MySQL/MariaDB は特定または複数のフィールドで重複データをクエリします

テストテーブルとデータを作成する

# 创建表
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() 関数を使用し、グループごとにグループ化し、グループ化してフィルター処理します。

select name, count(*) count
from t_duplicate
group by name
having count > 1;
  • group by name:nameフィールドごとにグループ化します。
  • count(*): 各グループ内のレコード数を計算します。
  • having count > 1: グループ化後、レコード番号が 1 より大きいグループをフィルタリングします。

検索結果:

名前 カウント
ある 2

サブクエリと in 関数の使用

select *
from t_duplicate
where name in (
  select name
  from t_duplicate
  group by name
  having count(*) > 1
)
  • サブクエリ: グループ化に従ってname、レコード番号が 1 より大きいグループをフィルタリングします。つまり、クエリが繰り返されますname
  • 外部クエリ:重複レコードinをフィルタリングするために使用しますname

検索結果:

名前
ある 1
ある 2

ウィンドウ関数を使用してパーティションごとに分割する

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値が 1 つのパーティション内にあります。
  • count(*) over: 各パーティションのレコード数をカウントします。
  • count > 1: パーティション レコード番号 > 1 のデータをフィルターします。

検索結果:

名前 カウント
ある 2
ある 2

複数のフィールドの重複をクエリする

……

おすすめ

転載: blog.csdn.net/duanluan/article/details/132730114