简体   繁体   English

联接替换子查询

[英]Join to replace sub-query

I am almost a novie in database queries. 我在数据库查询中几乎是个菜鸟。 However,I do understand why and how correlated subqueries are expensive and best avoided. 但是,我确实理解为什么以及如何避免关联子查询昂贵且最好避免。 Given the following simple example - could someone help replacing with a join to help understand how it scores better: 给出以下简单示例-有人可以帮助替换为联接,以帮助理解它的得分如何提高:

SQL> select
  2    book_key,
  3    store_key,
  4    quantity
  5  from
  6    sales s
  7  where
  8    quantity < (select max(quantity)
  9                 from sales
 10                 where book_key = s.book_key); 

Apart from join,what other option do we have to avoid the subquery. 除了连接,还有什么其他选择可以避免子查询。

In this case, it ought to be better to use a windowed-function on a single access to the table - like so: 在这种情况下,最好是在对表的单次访问上使用窗口函数-像这样:

with s as
(select book_key, 
        store_key, 
        quantity, 
        max(quantity) over (partition by book_key) mq
 from sales)
select book_key, store_key, quantity
from s 
where quantity < s.mq

Using Common Table Expressions (CTE) will allow you to execute a single primary SELECT statement and store the result in a temporary result set. 使用通用表表达式 (CTE)将使您能够执行单个主SELECT语句并将结果存储在临时结果集中。 The data can then be self-referenced and accessed multiple times without requiring the initial SELECT statement to be executed again and won't require possibly expensive JOINs. 然后,可以对数据进行自我引用和多次访问,而无需再次执行初始的SELECT语句,并且不需要昂贵的JOIN。 This solution also uses ROW_NUMBER() and the OVER clause to number the matching BOOK_KEYs in descending order based off of the quantity. 此解决方案还使用ROW_NUMBER()OVER子句根据数量从小到大对匹配的BOOK_KEY进行编号。 You will then only include the records that have a quantity that is less than the max quantity for each BOOK_KEY. 然后,您将仅包括数量少于每个BOOK_KEY的最大数量的记录。

with CTE as
(
  select 
    book_key, 
    store_key, 
    quantity,
    row_number() over(partition by book_key order by quantity desc) rn
  from sales
)
select 
  book_key, 
  store_key, 
  quantity 
from CTE where rn > 1;

Working Demo: http://sqlfiddle.com/#!3/f0051/1 工作演示: http : //sqlfiddle.com/#!3/f0051/1

Apart from join,what other option do we have to avoid the subquery. 除了连接,还有什么其他选择可以避免子查询。

You use something like this: 您使用类似这样的东西:

SELECT select max(quantity)
INTO @myvar 
from sales
where book_key = s.book_key

select book_key,store_key,quantity
from sales s
where quantity < @myvar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM