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?

INSERT ... SELECT の基本形

0
Posted at

前提

例えば

INSERT INTO details (
    denpyo_no,
    meisai_id,
    item_name
)
SELECT
    100,
    1,
    'りんご';

これは実行できます。

つまり、

SELECT
    100,
    1,
    'りんご'

VALUES (
    100,
    1,
    'りんご'
)

とほぼ同じ役割になります。
SELECTでは必ずしもテーブルのカラムを指定する必要はありません。

LaravelでINSERT ... SELECT

INSERT INTO details (  
    denpyo_no,  
    meisai_id,  
    item_name  
)  
SELECT  
    :denpyo_no,  
    :meisai_id,  
    :item_name  
WHERE NOT EXISTS (  
    SELECT 1  
      FROM details  
     WHERE denpyo_no = :denpyo_no  
       AND meisai_id = :meisai_id  
)

WHERE NOT EXISTS がどう効くのか

SELECT
    :denpyo_no,
    :meisai_id,
    :item_name
WHERE NOT EXISTS (
    SELECT 1
      FROM details
     WHERE denpyo_no = :denpyo_no
       AND meisai_id = :meisai_id
)

の部分について、

存在しない場合

SELECT 100,1,'りんご'
WHERE NOT EXISTS (...)

結果1件挿入

存在する場合

SELECT 100,1,'りんご'
WHERE NOT EXISTS (...)

結果0件
(何も返らない


つまり

INSERT INTO details (...)
SELECT ...

は、
SELECTが1件返したらINSERT
SELECTが0件ならINSERTしない
という動きになります。

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?