2015-07-21 41 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

相关问题