跨SQL集操作的WHERE子句

时间:2012-08-10 02:29:23

标签: sql

考虑以下查询,其中两个集合都需要通过相同的Location进行过滤。是否有更高效/高效的方法,Location过滤器只在两个集合中应用一次,或者您是否被迫对每个集合应用相同的过滤器?

SELECT *
FROM   Orders
WHERE  Quantity BETWEEN 1 AND 100
AND Location = 'SE'

EXCEPT

SELECT *
FROM   Orders
WHERE  Quantity BETWEEN 50 AND 75
AND Location = 'SE';

注意:不打算重构设置操作本身只是一个虚拟的例子。我的问题只是关于如何处理集合操作中的常见WHERE子句。

6 个答案:

答案 0 :(得分:4)

我会将查询重新计算为:

SELECT *
FROM Orders
WHERE Quantity BETWEEN 1 AND 100
AND Quantity NOT BETWEEN 50 AND 75
AND Location = 'SE';

答案 1 :(得分:1)

您可以使用CTE

执行此操作
with ord (Column1, Column2) as
(
    SELECT Column1, Column2
    FROM Orders 
    WHERE Location = 'SE'
)
SELECT *
FROM ord
WHERE Quantity BETWEEN 1 AND 100

EXCEPT

SELECT *
FROM ord
WHERE Quantity BETWEEN 50 AND 75

如果CTE不可用,您可以使用视图执行相同的操作。

答案 2 :(得分:1)

您可以使用AND NOT而不是EXCEPT [1]来处理设置操作,并在不同平台上提供更多支持。

我认为值得一提的是一个总结:

  1. 首先放置最不可能的表达。
  2. 首先放置最不复杂的表达式。
  3. 使用更多和更少的搜索。
  4. 反向点1&如果您使用Oracle,则由于从右到左的评估,而不是从左到右。

答案 3 :(得分:0)

SELECT *
FROM   Orders
WHERE  ((Quantity BETWEEN 1 AND 49) OR (Quantity BETWEEN 76 AND 100))
AND Location = 'SE'

尝试此查询并确保其获取相同的结果。

答案 4 :(得分:0)

我会这样做:

SELECT *
FROM   Orders
WHERE  ((Quantity BETWEEN 1 AND 49)
OR (Quantity BETWEEN 76 AND 100))
AND Location = 'SE';

答案 5 :(得分:-1)

SELECT * 
FROM   Orders o1
WHERE  Quantity BETWEEN 1 AND 100 
AND Location = 'SE'
AND NOT EXISTS ( SELECT 1 FROM ORDERS o2 
                 WHERE QUANTITY BETWEEN 50 AND 75 
                 AND Location = 'SE' 
                 AND o1.ORDERS_ID = o2.ORDERS_ID)