简体   繁体   中英

MySQL and FOREIGN KEY. Disallow NULL on allowed NULL value column

Example of tables

t1:

__________
|id | val|
|---+----|
| 1 | a  |
|---+----|
| 2 | b  |
|---+----|
| 3 | c  |
|---+----|


t2:
__________
|id | val|
|---+----|
| 1 | d  |
|---+----|
| 2 | e  |
|---+----|
| 3 | f  |
|---+----|
T:
    ________________________________
    |id | val| fk_t1_id | fk_t2_id |
    |---+----|----------+----------|
    | 1 | g  |    1     |   NULL   |
    |---+----|----------+----------|
    | 2 | h  |    NUL   |    1     |
    |---+----|----------+----------|
    | 3 | i  |    3     |   NULL   |
    |---+----|----------+----------|

Both 'fk_t1_id' and 'fk_t2_id' are foreign keys fileds and both are NULL allowed. Is it possible to make additional constraint which will allows only 1 FK on one field and NULL on another? (to be impossible insert row where both 'fk_t1_id' and 'fk_t2_id' are NULL or both of it are NOT NULL)

Create a check constraint on the T table having condition:
CHECK( (fk_t1_id is not NULL and fk_t2_id is NULL) OR (fk_t1_id is NULL and fk_t2_id is NOT NULL))

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