繁体   English   中英

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

[英]How do I set default value for a foreign key column in mysql

                       table1                    

            bookid     bookname         author
             0         No book           no author
             1         Engg Maths        Greiwal
             2         Java Basics       James Gosling
             3         Mahabharata       Ved Vyasa
             4         Ramayana          Valmiki
             5         Harry Potter      JK Rowling


                    table2

           userid       name           bookid
            1          Arjun             2
            2          Charles           2
            3          Babbage           3

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

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

它将引发异常“无法添加或更新子行:外键约束失败”

为什么您有一排叫做“没有书”的行? 您在表格中需要的只是书籍,而不是“无书”,首先从table1中删除该无用的行,然后在table2中:允许外键为null,如果外键为null,则基本上意味着“无书”,现在“ null”是默认值,null表示您想要的是“ no book”

我只是在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,)。 如果您要构建大量代码,则允许外键为空或使用“前哨值”的选择是最明智的设计选择。

如果我了解您的问题,可能的两种解决方案

  1. table1应该具有默认行,而表2的默认值将引用它

  2. 允许将NULL值用作外键

允许空值或默认值-SQL Fiddle

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM