如何在mysql中设置外键列的默认值

时间:2015-11-19 07:15:04

标签: mysql jdbc table-relationships

K

我有table1和table2。在table1中,bookid是主键,table2 bookid是外键。我想将table2 bookid默认值设置为0。

有可能吗? 我们尝试将默认值设为零。

它抛出异常“无法添加或更新子行:外键constaint失败”

3 个答案:

答案 0 :(得分:3)

为什么你有一行名为"没有书"?你在表中所需要的只是书本,而不是“没有书”。 首先从table1中删除那个无用的行,然后在table2中删除: 允许外键为null,如果外键为null则表示"没有书" 基本上,现在" null"是默认值,null表示"没有书" 这就是你想要的

答案 1 :(得分:1)

我刚刚在mysql上运行了这个...

create table table1 (
    bookid int not null primary key,
    bookname varchar(100) not null,
    author varchar(100) not null
);

create table table2 (
    userid int not null,
    username varchar(100) not null,
    bookid int not null default 0
);
alter table table2 add constraint fk1 foreign key (bookid) references table1(bookid);

insert into table1(bookid,bookname,author) values (0,'None','none');

insert into table2(userid, username) values (1,'bob');

select * from table2;

结果

1    bob    0

你也可以使fk列table2.bookid可以为空(bookid int null,)。选择允许外键为空或使用' sentinel值'如果您要构建大量代码,那么这是一个有意识地做出的设计选择。

答案 2 :(得分:0)

如果我理解你的问题,可能有两个解决方案

  1. table1应该有默认行,而表2的默认值是指它

  2. 允许NULL值为外键

  3. Allowing null values or default values-SQL fiddle