您可以使用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
輸出: -
這可能是簡單的把技術/客戶/第三方成用一個字段來區分不同類型的派對。然後你可以使用外鍵來提高效率。如果您必須在不同的表格中有派對類型,則可以在票據表中分開字段,每個字段都是各種表格的外鍵。如果沒有更多細節(你的RDBMS,表結構),我不能得到更具體的結果:你的問題是非常開放的。 –
單個表的替代方案可能是將多個表的聯合作爲視圖呈現。表現可能不會很好,並且你有責任確保唯一的ID(如你已經是!)。如果數據庫是PostgreSQL,則可以使用表繼承並重新提供各個表。 –
只有這三方或更多? –