您可以使用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,则可以使用表继承并重新提供各个表。 –
只有这三方或更多? –