如果在mysql中违反约束条件,则插入null?
问题描述:
我有一个国家,让我们说用户表,并且如果提交的国家与约束不匹配,我希望null去那里。如果在mysql中违反约束条件,则插入null?
create table countries(
ccode char(2), primary key (ccode)
);
create table users(
ccode char(2), foreign key (ccode) references countries(ccode)
);
insert into countries values('ru'),('us'),('hk');
现在,如果用户提交一个不存在的代码,例如:
insert into users values('xx');
- 查询实际上不能因FK constaint。但我希望它写一个空值。我们应该怎么做?
答
回答我的问题看起来这是做它的方式:
(但如果你提出一个更好的答案,我会接受它当然)
insert into users values((select ccode from countries where ccode='x'));
^这将返回一个代码,如果不匹配则返回null - 这是我想要的。