Gui*_*rez 29 sql-server performance pivot join sql-server-2005
在SQL Server 2005中使用什么更有效:PIVOT还是MULTIPLE JOIN?
例如,我使用两个连接获得此查询:
SELECT p.name, pc1.code as code1, pc2.code as code2
FROM product p
INNER JOIN product_code pc1
ON p.product_id=pc1.product_id AND pc1.type=1
INNER JOIN product_code pc2
ON p.product_id=pc2.product_id AND pc2.type=2
Run Code Online (Sandbox Code Playgroud)
我可以使用PIVOT做同样的事情:
SELECT name, [1] as code1, [2] as code2
FROM (
SELECT p.name, pc.type, pc.code
FROM product p
INNER JOIN product_code pc
ON p.product_id=pc.product_id
WHERE pc.type IN (1,2)) prods1
PIVOT(
MAX(code) FOR type IN ([1], [2])) prods2
Run Code Online (Sandbox Code Playgroud)
哪一个会更有效率?
Mar*_*ith 33
答案当然是"它取决于",但基于测试这一目的......
假设
product 有一个聚集索引 product_idproduct_code表中都有相应的信息product_code两个查询都有理想的索引.PIVOT理想情况下,该版本需要索引,product_code(product_id, type) INCLUDE (code)而理想JOIN版本需要索引product_code(type,product_id) INCLUDE (code)
如果这些已经到位,给出了以下计划

然后JOIN版本更有效.
在表中type 1并且type 2是types表中唯一的情况下,PIVOT版本稍微具有读取数量的优势,因为它不需要寻找product_code两次,但这比流聚合运算符的额外开销更重要
Table 'product_code'. Scan count 1, logical reads 10467
Table 'product'. Scan count 1, logical reads 4750
CPU time = 3297 ms, elapsed time = 3260 ms.
Run Code Online (Sandbox Code Playgroud)
Table 'product_code'. Scan count 2, logical reads 10471
Table 'product'. Scan count 1, logical reads 4750
CPU time = 1906 ms, elapsed time = 1866 ms.
Run Code Online (Sandbox Code Playgroud)
如果有更多的type比其他的记录1和2该JOIN版本将增加它的优势,因为它只是合并连接上的相关部分type,product_id指标,而PIVOT计划使用product_id, type,因此将不得不扫描整个额外type被混合在一起的行1和2列.
| 归档时间: |
|
| 查看次数: |
22783 次 |
| 最近记录: |