简体   繁体   中英

Composite foreign key constraint

The composite foreign key indexes do not work as I thought it would. In the following example, I want only the 10 combinations to be allowed in the child table. But the last insert statement is successful even if there is no matching combination in the parent table. Is there any other way to achieve that kind of constraint?

drop table if exists child;
drop table if exists parent;

CREATE TABLE parent(
`ID` int(11) default NULL,
`name` varchar(100) default NULL,
`city` varchar(100) default NULL,
key (name,city),
key (ID)
) ENGINE=InnoDB;

create table child(
userID int not null,
`name` varchar(100) default NULL,
`city` varchar(100) default NULL,
key (name,city),
FOREIGN KEY (name,city) REFERENCES parent(name,city),
primary key (userID)
) ENGINE=InnoDB;

insert into parent values (1, 'Amar', 'mumbai');
insert into parent values (2, 'Amar', 'Delhi');
insert into parent values (3, 'Amar', NULL);
insert into parent values (4, 'Akbar', 'mumbai');
insert into parent values (5, 'Akbar', 'Delhi');
insert into parent values (6, 'Akbar', NULL);
insert into parent values (7, 'Anthony', 'mumbai');
insert into parent values (8, 'Anthony', 'Delhi');
insert into parent values (9, 'Anthony', NULL);
insert into parent values (10, NULL, NULL);

insert into child values (2, NULL, 'mumbai');

Don't use nulls in foreign key columns; that way leads to the dark side. You should declare such columns NOT NULL .

According to the documentation

The MATCH clause in the SQL standard controls how NULL values in a composite (multiple- column) foreign key are handled when comparing to a primary key. InnoDB essentially implements the semantics defined by MATCH SIMPLE, which permit a foreign key to be all or partially NULL. In that case, the (child table) row containing such a foreign key is permitted to be inserted, and does not match any row in the referenced (parent) table. It is possible to implement other semantics using triggers.

since child.name field declared nullable it can contain null values. it does not violate foreign key concept. the solution is to decalre fk fields as 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