简体   繁体   中英

How to get correct constraints in SQL

I have a basic schema:

CREATE TABLE Human (
 hid INTEGER PRIMARY KEY,
 name VARCHAR(50),
 gender CHAR(1),
 dob DATE
);
CREATE TABLE Wed (
 husbd INTEGER REFERENCES Human(id),
 spouse  INTEGER REFERENCES Human(id),
 wedSince DATE,
 PRIMARY KEY (husbd, spouse)
 ); 

In this schema, every couple can be married exactly once... but I don't really see why. Could someone explain? How would I allow separations and re-marriages of the same couple?

Perhaps in the data each couple can be married only once. However, this schema does not enforce that constraint. The problem is that (A, B) and (B, A) are both allowed.

This is easy enough to fix by adding a check constraint on the spouses. I would go for:

CREATE TABLE Wed (
    spouse1 INTEGER REFERENCES Human(hid),
    spouse2 INTEGER REFERENCES Human(hid),
    wedSince DATE,
    PRIMARY KEY (spouse1, spouse2),
    CHECK (spouse1 < spouse2)
); 

The last constraint guarantees what you want. The last condition guarantees that (spouse1, spouse2) and (spouse2, spouse1) are not both in the table. Do note that this still allows one spouse to be married to multiple other people -- in most parts of the world, this would imply divorce or widowhood.

As a point of reference, many countries recognize same-sex couples, so there is no guarantee that one of the spouses is a "husband".

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