首页 > 解决方案 > 使用计算和联接时的最佳实践

问题描述

当一个人有一个 SQL 查询时,我有一个关于最佳实践的一般问题,并且您想使用联接/子查询来计算度量,然后将其用于业务规则。我学到了两种特别的方法,但是随着我的职业发展和我认识的人越来越多,他们似乎更喜欢其他方法。

下面,我写了我所指的5个例子。请注意,它们并不是用来工作的 SQL 查询,只是显示不同方法的示例。

--Example 1:  filtering in-line
select top 1
 from [Temp Data] base
 left join table1 t1    on base.key = t1.key
                        and t1.category = 1
                        and t1.status not in ('Voided', 'Deleted')

--Example 2: using where
select top 1
 from [Temp Data] base
 left join table1 t1    on base.key = t1.key
 where t1.category = 1
    and t1.status not in ('Voided', 'Deleted')


--Example 3: sub-query
select top 1
 from [Temp Data] base
 left join (select col1
                from table1 t1  
                where category = 1
                    and status not in ('Voided', 'Deleted')
                ) t1 on base.key = t1.key


--Example 4: if exists
select top 1
        ,case
            when exists (select col1
                            from table1 t1  
                            where category = 1
                                and status not in ('Voided', 'Deleted')
                                and base.key = t1.key
                        ) then 1
          else 0
         end
 from [Temp Data] base


 --Example 5: outer apply
 select top 1
 from [Temp Data] base
 outer apply (select col1
                from table1 t1  
                where category = 1
                    and status not in ('Voided', 'Deleted')
                    and base.key = t1.key
                ) t1 

我想听听人们对不同方法的看法。

标签: sqltsql

解决方案


查询做不同的事情。所以,你应该选择你想要的形式。

例如,第二个查询将left join转换为内连接。

第四个根本没有过滤,只是设置一个标志。

第一个、第三个和第五个是等价的。我认为第一种方法是编写查询的更“传统”方式——或者至少我认为更多的人会这样写。(3) 中的子查询是多余的(尽管对性能没有损害)。并且cross apply并非所有数据库都支持。


推荐阅读