MySQL insert where not exists / if not exists

前端 未结 1 826
死守一世寂寞
死守一世寂寞 2021-01-25 22:01

I have tried the following query:

INSERT INTO `surfed_site` (user, site)
VALUES (\'123\', \'456\')
WHERE NOT EXISTS (SELECT site FROM `surfed_site` WHERE site=456         


        
1条回答
  •  -上瘾入骨i
    2021-01-25 22:23

    INSERT statements support two1 syntaxes: one that uses VALUES, and one that uses a query. You can't combine them, and only the query syntax supports WHERE clauses. So:

    INSERT INTO `surfed_site` (user, site)
    SELECT '123', '456' FROM (SELECT 1) t
    WHERE NOT EXISTS (SELECT site FROM `surfed_site` WHERE site=456)
    

    1. Actually three syntaxes; you can also use SET. If you're only inserting one record, this one is functionally equivalent to VALUES, but arguably more readable.

    0 讨论(0)
提交回复
热议问题