2012-11-11 102 views
0

我正在爲我的網站創建一個數據庫,這需要用戶在不同的頁面上載多個附件。我希望將所有這些附件保存在一張表中,並從其他表中引用該表,並在其中需要附件。保存附件的數據庫表

現在的問題是我該如何做到這一點?我還沒有弄清楚它的邏輯。我想到的是:

attachment_tbl: 
attach_id 
file_name 
description 
item1_id -> FK 
item2_id -> FK 


item1_tbl: 
item1_id 
attachment1 
attachment2 


item2_tbl: 
item2_id 
attachment1 
attachment2 
attachment3 

現在我該怎樣保存所有這些附件在同一個表,在不attachment_tbl具有多FK,彷彿我再添item3_tbl,其中有附件,這將意味着另一FK被添加到attachments_tbl?

有沒有其他更簡單和更好的方法來做同樣的事情?

回答

3

添加一個關係表,連接項目和附件,具有一對多的關係:

attachment_tbl: 
attach_id 
file_name 
description 

item_tbl: 
item_id 

item_attachment_tbl: 
item_id -> FK 
attach_id -> FK 

對於每個附件,就會出現在item_attach表中的一行:

item_id attach_id 
----------------- 
item1 attach1 
item1 attach2 
item2 attach3 
item3 attach4 
item3 attach5 
item3 attach6 

當你想看到一個物品的附件,你必須加入表格:

select a.file_name, a.description 
from attachment_tbl a 
inner join item_attachment_tbl ia on a.attach_id = ia.attach_id 
where ia.item_id = 87; 

另請參見SQL Fiddle

+0

我想到了這一點,但它會不會引入額外的性能打擊?對於多重「ITEM_TBL」,這也不會在「ITEM_ATTACH_TBL」中引入多個字段嗎? – gagneet

+0

如果你有一對多的關係,那就是要走的路。您必須將連接存儲在某個位置,並且如果每個附件數都有一個表格,您會在哪裏停止? 10或20桌?另請參閱修改後的答案。 –

0

如果您不想在attachment_tbl中使用多個foreign_keys,那麼您需要以任何代價都擁有一個橋接表(如果您想保留該關係:)但它需要額外的字段作爲item_tbl_name來區分不同項目表的記錄。提取它們並不那麼複雜。

item_attachment_tbl: 
item_id -> FK 
item_tbl_name 
attach_id -> FK