2015-11-19 58 views
0
     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.如何在mysql中爲外鍵列設置默認值

是否有任何可能性? 我們嘗試使用默認值爲零。

它拋出一個異常 「不能添加或更新子行,外鍵constaint失敗」

+0

*我們嘗試用默認的.... *。請發佈您嘗試的sql查詢。 –

+0

我們使用的是SQLYog工具。在該alter table中,我們有一個名爲Default的列。我們將這些值更改爲零並保存。 – Aoryouncellvan

+0

在table2失敗後發佈'show create table1;'和'show create table2;'和'insert'語句的結果。 –

回答

0

我只是跑這對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,)。如果您打算構建大量代碼,那麼允許外鍵爲空或使用「哨兵值」的選擇是最有意識的設計選擇。

+0

它也適用於我。但我問表2中的bookid是一個外鍵。所以只有它不接受默認值。 – Aoryouncellvan

+0

謝謝@joshp。這對我來說可以。 – Aoryouncellvan

2

爲什麼你有一個叫「無書」的行?所有你需要的表格都是書籍,而不是「沒有書籍」 首先從table1中刪除那些無用的行,然後在表2中: 允許外鍵爲空,如果外鍵爲null那麼這意味着「無書」 基本上,現在的「空」是默認值,而空意思是「無書」 這是你想要什麼