简体   繁体   中英

MySQL check 2 values already exists before insert

My columns are like this. column "a" is primary and auto incremantal.

a |  b |  x  |  y

When inserting new data, i need to check x and y columns shouldn't be exist together.

To clarify, imagine this row is at database with these values

(2, "example.com" , "admin", "123456")

I should able to insert both of these columns

(3, "example.com" , "user", "123456")
(4, "example2.com" , "admin", "123456")

But i shouldn't able to insert this column

(5, "example.com" , "admin", "5555555")

Because "example.com" and "admin" values already in database on a row. It doesn't matter column "y" is same or not.

How can i do this?

Create a composite unique index. This will allow any number of duplicates in the individual fields, but the combination needs to be unique. CREATE UNIQUE INDEX ix_uq ON tablename (b, x);

...and use INSERT IGNORE to insert if the unique index is not violated. If it is, just ignore the insert.

INSERT IGNORE INTO test (a,b,x,y) VALUES (5, "example.com" , "admin", "5555555");

If you want to insert unless there's a duplicate, and update if there is, you can also use INSERT INTO ... ON DUPLICATE KEY UPDATE;

Ref: MySQL only insert new row if combination of columns (which allow duplicates) is unique

You want to let the database do the work. Although you can set up a condition within a query, that condition may not be universally true or someone might use another query.

The database can check this with a unique constraint or index. Actually, the unique constraint is implementing using a unique index:

create unique index unq_t_b_x on t(b, x);

(The columns can be in either order.)

The insert would then look like:

insert into t(b, x, y)
    values ('example.com', 'admin', '5555555')
    on duplicate key update b = values(b);

Note that the auto-incremented value is not included in the update.

The on duplicate key update just prevents the insert from generating an error. It is better than insert ignore because the latter will ignore all errors, and you just want to ignore the one caused by the duplicate key.

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