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 3 years have passed since last update.

INSERT を重複せずに実行する

Last updated at Posted at 2020-08-09

あるテーブルに重複有無を確認後、重複がなれけばINSERTしたいときの方法。

例えば users_booksテーブルが以下のようにあったとします。

id user_id book_id
1 5 10

ここで重複の有無を確認して、同じレコードが入っていないときINSERTしたいなら、以下のSQL文でできました。

INSERT INTO users_books(user_id, book_id) 
SELECT 5, 10, 
WHERE NOT EXISTS (SELECT user_id FROM users_books WHERE user_id = 5 AND book_id = 10)

注意する点として、通常のINSERTなら VALUESとなっているところが、SELECTになっていること。

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?