2017-06-29 99 views
0

我正在建立一個問題和答案網站,我有兩個表截至目前(問題和答案)我需要答案表的id字段是問題表中的外鍵,所以我可以有多個答案鏈接到一個問題。當我把不空的PHP代碼不會工作?這裏是我的表:當它應該是一個int時,說「NULL」的外鍵?

create table answers (
    a_id int not null auto_increment, 
    answer varchar(100) not null, 
    primary key (a_id) 
); 

create table questions (
    q_id int not null auto_increment, 
    question varchar(100) not null, 
    a_id int, 
    primary key (q_id), 
    foreign key (a_id) references answers (a_id) 
); 

我需要有外鍵部分中的號碼,這樣用戶可以看到所有的答案,他或她的問題。我在網上搜索了幾個小時,所以我來到了stackoverflow。我希望有人能幫幫忙!

+1

歡迎來到Stack Overflow。你可以用'{}'工具欄按鈕格式化源代碼。這次我爲你做了。 –

+0

因此,PHP代碼不起作用......你不認爲這是我們需要看到的部分嗎?它產生了什麼錯誤? – Jacobm001

+1

使用您當前的設計,問題可以有零個或一個答案,答案不一定需要問題。如果你想要一個測驗類型的應用程序,你的設計就會顛倒過來。如果你想要1個問題1個答案的應用程序,你並不需要兩個表。 –

回答

3

表格「答案」是不是有外鍵參考問題a_id?就像下面這樣:

create table questions (
    q_id int not null auto_increment 
    , question varchar(100) not null 
    , primary key (q_id) 
); 

create table answers (
    a_id int not null auto_increment 
    , answer varchar(100) not null 
    , q_id int not null 
    , primary key (a_id) 
    , foreign key (q_id) references questions(q_id) 
); 

也許我錯過了一些東西,但這將是我的想法。

+1

謝謝。幾個小時前我曾嘗試過,並認爲我得到了相同的結果,但我會再試一次。 – do734

+0

如果這不適合你,這可能是你寫/讀數據的方式,我需要更多的信息來幫助。 – NicKJones

+1

我複製並粘貼您的表到我的系統和訂單工作正常,但對於答案表我得到了「錯誤1064(42000):您的SQL語法錯誤;檢查對應於您的MySQL服務器版本的手冊(a_id) ,外鍵(q_id)引用問題(q_id) )在'第5行' – do734

相關問題