2015-07-21 39 views
0

我正在設計一個簡單的辦公室內票務系統,並且希望爲負責下一個操作的一方添加一個字段。爲此目的,我正在考慮使用tableNametableID作爲特定責任方(可能是技術員,客戶或第三方,所有人都在不同的表格中)的說明符如何使用連接語句從多個SQL表中獲取數據

這樣可以很好地拉動數據輸入並使用表名作爲參數運行另一個選擇調用,但額外的數據流會顯着降低速度。

是否有一種方法可以使用單個聯接語句來返回該表的名稱列和一個單獨的表id標識的聚會詳細信息,還是有更好的方法來存儲來自多個潛在表的數據嗎?

+1

這可能是簡單的把技術/客戶/第三方成用一個字段來區分不同類型的派對。然後你可以使用外鍵來提高效率。如果您必須在不同的表格中有派對類型,則可以在票據表中分開字段,每個字段都是各種表格的外鍵。如果沒有更多細節(你的RDBMS,表結構),我不能得到更具體的結果:你的問題是非常開放的。 –

+0

單個表的替代方案可能是將多個表的聯合作爲視圖呈現。表現可能不會很好,並且你有責任確保唯一的ID(如你已經是!)。如果數據庫是PostgreSQL,則可以使用表繼承並重新提供各個表。 –

+0

只有這三方或更多? –

回答

0

您可以使用LEFT JOIN來實現您的要求: -

Set Nocount On; 

Declare @OfficeTickets Table 
(
    Id    Int Identity(1,1) 
    ,Column1  Varchar(100) 
    ,PartyType  Varchar(1) 
    ,TechnicianId Int Null 
    ,CustomerId  Int Null 
    ,ThirdPartyId Int Null 
) 

Declare @OfficeTickets1 Table 
(
    Id    Int Identity(1,1) 
    ,Column1  Varchar(100) 
    ,TableName  Varchar(100) 
    ,TableId  Int Null 
) 

Declare @Technician Table 
(
    Id    Int Identity(1,1) 
    ,TechnicianName Varchar(100) 
) 

Declare @Customers Table 
(
    Id    Int Identity(1,1) 
    ,CustomerName Varchar(100) 
) 

Declare @ThirdParty Table 
(
    Id    Int Identity(1,1) 
    ,ThirdPartyName Varchar(100) 
) 

Insert Into @Technician(TechnicianName) Values 
('Technician_1') 
,('Technician_2') 
,('Technician_3') 

Insert Into @Customers(CustomerName) Values 
('Customer_1') 
,('Customer_2') 
,('Customer_3') 

Insert Into @ThirdParty(ThirdPartyName) Values 
('ThirdParty_1') 
,('ThirdParty_2') 
,('ThirdParty_3') 
,('ThirdParty_4') 

Insert Into @OfficeTickets(Column1,PartyType,TechnicianId,CustomerId,ThirdPartyId) Values 
('ABC','T',3,Null,Null) 
,('XYZ','C',Null,2,Null) 
,('PUQ','P',Null,Null,4) 

Insert Into @OfficeTickets1(Column1,TableName,TableId) Values 
('ABC','Technician',3) 
,('XYZ','Customers',2) 
,('PUQ','ThirdParty',4) 

---- taken separate columns for parties 
Select ot.Id 
     ,ot.Column1 
     ,t.TechnicianName 
     ,c.CustomerName 
     ,tp.ThirdPartyName 
From @OfficeTickets As ot 
     Left Join @Technician As t On ot.PartyType = 'T' And ot.TechnicianId = t.Id 
     Left Join @Customers As c On ot.PartyType = 'C' And ot.CustomerId = c.Id 
     Left Join @ThirdParty As tp On ot.PartyType = 'P' And ot.ThirdPartyId = tp.Id 

---- by TableName and TableId 
Select ot.Id 
     ,ot.Column1 
     ,t.TechnicianName 
     ,c.CustomerName 
     ,tp.ThirdPartyName 
From @OfficeTickets1 As ot 
     Left Join @Technician As t On ot.TableName = 'Technician' And ot.TableId = t.Id 
     Left Join @Customers As c On ot.TableName = 'Customers' And ot.TableId = c.Id 
     Left Join @ThirdParty As tp On ot.TableName = 'ThirdParty' And ot.TableId = tp.Id 

輸出: -

enter image description here

相關問題