3
1

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 2017-12-19

経緯

業務でテーブル内の重複データを削除する必要があったために使用したSQLです
データのidが必要だったために使用したSELECT文です
運用等でSQLを考える時の参考になればと思います

実行環境

Mysql 5.6

ここでの重複データとは?

例:tagsテーブル

article_id title position
1 rails 1
1 python 2
2 ruby 3
1 rails 2
1 python 3
3 ruby 4
  • column1(title)の値が同一でcolumn2(position)が異なる値のもの
  • 異なる値とはここではpositionが1ずれている

どんなSELECT文?

削除対象がpositionの値が大きい方なので、そちらを取得してます

削除対象を取得するSELECT文
SELECT
  t2.id, (t2.position + 1)
FROM
  tags t1
INNER JOIN
  tags t2
ON
  t1.article_id = t2.article_id
WHERE
  t1.position = t2.position + 1
  AND
  t1.title = t2.title
;  

Deleteする場合はどんなSQL文?

先程書いたSELECT文で対象のidを取得し、それを元にdeleteしています

取得したidを元に削除するDELETE文
DELETE
FROM
  tags
WHERE
  id IN (
    SELECT id FROM (
      SELECT
        t1.id
      FROM
        tags t1
      INNER JOIN
        tags t2
      ON
        t1.article_id = t2.article_id
      WHERE
        t1.position = t2.position + 1
        AND
        t1.title = t2.title
    ) AS tmp
  )
;

編集履歴

  1. deleteするSQLがうまく動作しなかったので、変更しました。同じテーブルに対するサブクエリからの操作は出来ない為です

参考サイト

MySQLでERROR:1093を回避する

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?