简体   繁体   中英

MySQL insert if not exists/ignore

So basically here's my table layout:

Type_Of     Agreement
iPad        Heyo! I'm an agreement!
iPod Touch  I'm another agreement!

Basically, I'm building an admin interface where an administrator can add new types. I'd like it to make it so he/she can't enter a new type that already exists. Basically, in the above example, if they were to enter 'iPad' in the new type box and press submit, it will simply be ignored or an error will be thrown or something.

Here's my existing MySQL statement:

INSERT IGNORE INTO agreements (Type_Of, Agreement) VALUES (?, ?)
com.Parameters.AddWithValue("", Request.Form["pies"]);
com.Parameters.AddWithValue("", "Wahey! A sample license!");

( Upgrading to an answer )

You need to define a UNIQUE index on Type_Of . As explained in the manual :

A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL . If you specify a prefix value for a column in a UNIQUE index, the column values must be unique within the prefix.

Therefore:

ALTER TABLE agreements ADD UNIQUE INDEX (Type_Of);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM