簡體   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