简体   繁体   中英

Insert only if two columns don't have the same value for each one of them on the same row

If I have a table like

id            col1         col2             col3
1             John         Edward           any OK
2             John         David            any OK
3             John         Sam              any OK
4             David        Sam              any OK
5             John         Sam              any * Not allowed it already exists.

So, John can be repeated on col1, but it is not allowed to repeat John and Sam on col1 and col2.

col1 and col2 are not unique.

How to do insert and update on that table in SQLite?

Just create a UNIQUE constraint that spans col1 and col2 :

CREATE TABLE table_name(
    id INTEGER PRIMARY KEY,
    col1 TEXT,
    col2 TEXT,
    col3 TEXT,
    UNIQUE(col1, col2)
);

In your application, just handle the constraint violation exception.

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