Is it possible to insert a row but only if a value does not already exist?

前端 未结 7 1844
谎友^
谎友^ 2021-02-04 05:26

Is it possible to insert a row, but only if one of the values already in the table does not exist?

I\'m creating a Tell A Friend with referral points for an eco

7条回答
  •  余生分开走
    2021-02-04 05:58

    If the column is a primary key or a unique index:

    INSERT INTO table (email) VALUES (email_address) ON DUPLICATE KEY UPDATE
    email=email_address
    

    Knowing my luck there's a better way of doing it though. AFAIK there's no equivalent of "ON DUPLICATE KEY DO NOTHING" in MySQL. I'm not sure about the email=email_Address bit, you could play about and see if it works without you having to specify an action. As someone states above though, if it has unique constraints on it nothing will happen anyway. And if you want all email addresses in a table to be unique there's no reason to specify it as unique in your column definition.

提交回复
热议问题