TSQL: Using replace function in select with join(TSQL:在 select with join 中使用替换函数)
问题描述
背景.我正在使用 SQL Server.我在数据库中有两个表:
Background. I'm using SQL Server. I have two tables in database:
Vendors(Id, Name, Description)
Products(Id, VendorId, Name, Description)
Id 列中的值使用 Vendor 表中的前缀 'ID_' 进行格式化.
Values in Id column are formatted with prefix 'ID_' in Vendor table.
VendorId 列中的值使用 Products 表中的前缀 'VE_' 进行格式化.
Values in VendorId column are formatted with prefix 'VE_' in Products table.
例如 Products中的'VE_001245'是指Vendors中的'ID_001245'>.
(请不要提议改变这个概念,不关心数据库方案,不建议添加外键.只是为了说明.)
(Please, do not propose to change this concept, do not care about database scheme, do not suggest adding foreign key. All it is just for illustration.)
问题:以下哪个查询在性能方面最好,为什么?
Question: which one of following queries is best in performance context and why?
在内部
select中使用replace函数:
select v.* from Vendors v
inner join
(
select distinct replace(VendorId, 'VE_', 'ID_') as Id
from Products
) list
on v.Id = list.Id
在on语句中使用replace函数:
select v.* from Vendors v
inner join
(
select distinct VendorId as Id
from Products
) list
on v.Id = replace(list.Id, 'VE_', 'ID_')
编辑.每个表中只有聚集索引(按Id列).每个表可以包含数百万行.
Edit. There is only clustered index in each table (by Id column). Each table can contains millions rows.
推荐答案
两个查询在性能方面几乎相同.在第一个查询中,排序 进行了两次,一次是在选择不同记录时,一次是在执行内部联接时,最后是 合并联接选择最终结果集.而在第二个查询中,排序只完成一次,但正在执行 Hash join,这比合并连接更昂贵.因此,在表上没有任何索引的情况下,这两个查询在性能方面是相同的.
Both the queries are almost same in terms of performance. In the first query sorting is done twice, once when you are selecting the distinct records and again when it is performing an inner join, and in the end a merge join is there to select the final result set. Whereas in second query sorting is done only once but Hash join is being performed which is more expensive then merge join. So both the queries are same performance wise in the scenario when you don't have any index on the table.
这篇关于TSQL:在 select with join 中使用替换函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:TSQL:在 select with join 中使用替换函数
基础教程推荐
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 在 SQL 中连接多个表 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 无法解决整理冲突 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
