SQL结合两个连接

时间:2014-04-24 18:05:31

标签: sql join

我会说我对SQL的理解是平均的,但我想知道是否有任何方法可以更有效地编写此语句?

Company的主键是uniqentity,并且该行中的公司名称为nameof

在表格Line中,主键为uniqline,我有entityCompanyBillingentityCompanyIssuing列(uniqentity的两个外键)。

下面这段代码运行得很好,我只是想提高效率。有可能吗?

SELECT 
   l.uniqline, b.nameof AS billingcompany, 
   l.UniqEntityCompanyBilling, i.nameof AS issuingcompany, 
   l.UniqEntityCompanyIssuing
FROM 
   Line l 
INNER JOIN 
   Company b ON b.uniqentity = l.uniqentitycompanybilling
INNER JOIN 
   Company i ON i.uniqentity = l.uniqentitycompanyissuing 

3 个答案:

答案 0 :(得分:2)

更改查询的结构可能无法提高效率(它似乎很简单)。但是,更改数据的结构可能会:

  • UniqEntityCompanyBillingUniqEntityCompanyIssuing
  • 上添加索引(如果尚未添加)
  • Company.UniqEntity上添加索引 没有发现该列是PK
  • 如果Company.UniqEntity上的索引尚未群集,请在nameof的索引中添加Company.UniqEntity字段,以便查询不必返回物理表。

答案 1 :(得分:1)

此查询完全正常。

你可以把它缩短如下,但这会降低可读性,通常被认为是不好的做法,所以不要。

SELECT l.uniqline, b.nameof AS billingcompany, l.UniqEntityCompanyBilling, i.nameof AS issuingcompany, l.UniqEntityCompanyIssuing
FROM Line l, Company b, Company i
WHERE b.uniqentity = l.uniqentitycompanybilling
AND i.uniqentity = l.uniqentitycompanyissuing

答案 2 :(得分:1)

如果可能,您可以在加入表格时加入过滤器,如下所示:

SELECT 
   l.uniqline, b.nameof AS billingcompany, 
   l.UniqEntityCompanyBilling, i.nameof AS issuingcompany, 
   l.UniqEntityCompanyIssuing
FROM 
   Line l 
INNER JOIN 
   (SELECT *
    FROM Company
    WHERE <REGION = 'xyz', etc.>
   ) b ON b.uniqentity = l.uniqentitycompanybilling
INNER JOIN 
   (SELECT *
    FROM Company 
    WHERE <REGION = 'xyz', etc.>
   ) i ON i.uniqentity = l.uniqentitycompanyissuing
WHERE <any filter condition>;