0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

SQLで重複しているレコードだけ抽出する

Last updated at Posted at 2019-12-18

環境

MySQL
※多分他のやつでも同じように動くはず

やりたいこと

タイトルの通り、SQLの適当なテーブルから、特定のカラムの値が重複しているレコードだけを抽出。

コード

SELECT * FROM <テーブル> GROUP BY <カラム...> HAVING COUNT(*) >= 2;

ちなみに、カラムを複数対象にしたい場合には、GROUP BYに複数のカラム(「,」区切り)を書くことができます。

例) users テーブル(id,name_sei,name_mei,age,sex)

同姓同名がテーブルにいるアカウントのみ抽出

SELECT * FROM users GROUP BY name_sei,name_mei HAVING COUNT(*) >= 2;

最後に

SQLで全件検索した後にawkを使って無理やりやろうとしてましたが、冷静に考えてみたらSQLの方が素直に書けて良いですね。

SQLでかけるようなときは、AWK自重します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?