2012-10-03 36 views
1

我有一個概念性的問題,我希望有人更熟悉SQL數據庫設計可以幫助我。我有一個表格,其中每行在其他幾個表格之一中都有相應的行。 IE瀏覽器。表1中的行在表2,表3或表4中具有相應的行(但從不多於1 ...中,對應的行只能在其他表中的一箇中)。sql錶行在其他幾個表之一有相應的行

設置此結構的最佳方法是什麼?如果我在表1中放置一個othertable_id列和一個表名列,我可以保證在其他表中只有一個相應的行,但它似乎是一個非常不靈活的混亂解決方案。另一方面,如果我只在table2,table3和table4中放置table1_id列,似乎我需要在每次要查找與table1中的行對應的行時運行3個不同的查詢,並且它看起來像我無法保證在table1中我的行只有三個表中的任何一個條目。

有沒有人有任何建議?

+0

聽起來像你真正需要的是PostgreSQL的繼承ed tables ... – cdhowie

+0

你應該學習參照完整性... –

+0

這聽起來像一個相當不尋常的設置。你能否給我們一個更具體的例子來說明你想要做什麼?你可能不需要這麼多的表格。 – NullUserException

回答

2

我會使用第二種解決方案,並使用觸發器確保不存在多於一個相關行。

查詢看起來像:

select * 
from table1 t1 
left outer join table2 t2 on t1.id = t2.table1_id 
left outer join table3 t3 on t1.id = t3.table1_id 
left outer join table4 t4 on t1.id = t4.table1_id 

如果有你想要的表格,例如value之間的共同列,你可以得到這樣的:

select t1.*, 
    coalesce(t2.value, t3.value, t4.value) as value 
from table1 t1 
left outer join table2 t2 on t1.id = t2.table1_id 
left outer join table3 t3 on t1.id = t3.table1_id 
left outer join table4 t4 on t1.id = t4.table1_id 
+0

感謝您的詳細解答。這真的很有幫助! – akhalsa

+0

+1。如果不能找到不同的設計,這是一個關係正確和直接實施的好組合。 –

0

我想我沒有看到什麼是混亂的複合關鍵,建立你的關係的子表。如果這就是你的邏輯模型的工作原理,不要試圖過於聰明,並且試圖弄清楚依賴關係的任何人。

工作過的問題是用一個例子顯著容易,也許以下工作:

A college contains students, professors, and assistants. 
It needs to keep track of each individual's name and address. 
In addition it holds : 
    for students, their GPA 
    for professors, their office address 
    for assistants, their professor 

我工作起來類似於下面的模型:

person { person_id, name, address } 
student { person_id, gpa } 
professor { person_id, office_address } 
assistant { person_id, professor_id } 

當我去實現這我最有可能最終會像這樣:

CREATE TABLE person (
    person_id, type, name, address, 
    PK (person_id) 
) 

CREATE TABLE student (
    person_id, gpa, 
    PK(person_id), 
    FK(person_id to person.person_id), 
    CK(person.type = 'student') 
) 
相關問題