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

前端 未结 7 1837
谎友^
谎友^ 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:37

    This works if you have a unique index or primary key on the column (EmailAddr in this example):

    INSERT IGNORE INTO Table (EmailAddr) VALUES ('test@test.com')
    

    Using this if a record with that email already exists (duplicate key violation) instead of an error, the statement just fails and nothing is inserted.

    See the MySql docs for more information.

    0 讨论(0)
  • 2021-02-04 05:47

    I'm not sure if I got it, but what about a

    try {
      mysql_query($sql);
    }
    catch(Exception $e) {
    
    }
    

    combined with an unique field index in MySQL?

    if it throws an exception then you know that you got a duplicated field. Sorry if that don't answer your question..

    0 讨论(0)
  • 2021-02-04 05:55

    Most likely something like:

    IF NOT EXISTS(SELECT * FROM myTable WHERE Email=@Email) THEN INSERT INTO blah blah
    

    That can be rolled into one database query.

    0 讨论(0)
  • 2021-02-04 05:57

    If the email field was the primary key then the constraints on the table would stop a duplicate from being entered.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-04 05:58

    MySQL offers REPLACE INTO http://dev.mysql.com/doc/refman/5.0/en/replace.html:

    REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.

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