我对SQL Server查询比较陌生。
我正在尝试编写一个查询,显示我公司的分支。我有3种方法可以这样做:
编写子查询:
Select
(Select branchname
from branchtable
where branchPK = primarycompanybranchfk
) as branchone,
(Select branchname
from branchtable
where branchPK = secondarycompanybranchfk
) as branchtwo
from companytable
使用联接:
Select
a.branchname as branchone,
b.branchname as branchtwo
from companytable c
left join branchtable a
on a.branchPK = c.primarycompanybranchfk
left join branchtable b
on b.branchPK = c.secondarycompanybranchfk
使用子表连接:
Select
branchfirst.branchname as branchone,
branchsecond.branchname as branchtwo
from companytable c
left join (
Select branchPK as prikey,
branchname as branchname
from branchtable
) branchfirst
on branchfirst.prikey= c.primarycompanybranchfk
left join (
Select branchPK as prikey,
branchname as branchname
from branchtable
) branchsecond
on branchsecond.prikey= c.secondarycompanybranchfk
如果我使用第二个场景超过第二个场景,或者反之亦然,如果我的分支表包含超过10列,是否有任何性能提升?
答案 0 :(得分:0)
还有一个提示:-)尝试设置每个人都可以重现的样本。使用自己的表会使这更难......
在大多数情况下,2和3将完全相同,"嵌套列"在这种情况下是最快的:
尝试此操作并设置"包含执行计划"选项。因此,您可以在之后比较执行计划(还有两个变体CROSS APPLY
与2和3完全相同。)
究竟发生了什么 - 当然 - 在更复杂的情况下要复杂得多。这取决于现有的索引和统计数据。
SELECT c.COLUMN_NAME,
(SELECT t.TABLE_NAME FROM INFORMATION_SCHEMA.TABLES AS t WHERE c.TABLE_NAME=t.TABLE_NAME) AS TABLE_NAME
from INFORMATION_SCHEMA.COLUMNS as c
SELECT c.COLUMN_NAME,t.TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS as c
INNER JOIN INFORMATION_SCHEMA.TABLES AS t ON c.TABLE_NAME=t.TABLE_NAME
SELECT c.COLUMN_NAME,t.TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS as c
INNER JOIN (SELECT t.TABLE_NAME FROM INFORMATION_SCHEMA.TABLES AS t) AS t ON c.TABLE_NAME=t.TABLE_NAME
SELECT c.COLUMN_NAME,t.TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS as c
CROSS APPLY INFORMATION_SCHEMA.TABLES AS t
WHERE c.TABLE_NAME=t.TABLE_NAME
SELECT c.COLUMN_NAME,t.TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS as c
CROSS APPLY (SELECT t.TABLE_NAME FROM INFORMATION_SCHEMA.TABLES AS t WHERE c.TABLE_NAME=t.TABLE_NAME) AS t
答案 1 :(得分:0)
在这种情况下,两者将具有相同的性能,因为查询优化器将两者视为相同的查询。但是如果你在嵌套查询中有一个过滤器,那么它会更快。
很好地加入所需的数据量而不是完整的数据集。