我会说我对SQL的理解是平均的,但我想知道是否有任何方法可以更有效地编写此语句?
表Company
的主键是uniqentity
,并且该行中的公司名称为nameof
。
在表格Line
中,主键为uniqline
,我有entityCompanyBilling
和entityCompanyIssuing
列(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
答案 0 :(得分:2)
更改查询的结构可能无法提高效率(它似乎很简单)。但是,更改数据的结构可能会:
UniqEntityCompanyBilling
和UniqEntityCompanyIssuing
Company.UniqEntity
上添加索引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>;