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

前端 未结 7 1835
谎友^
谎友^ 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 06:01

    A slight modification/addition to naeblis's answer:

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

    This way you don't have to throw email=email_address in there and you get the correct value for LAST_INSERT_ID() if the statement updates.

    Source: MySQL Docs: 12.2.5.3

提交回复
热议问题