-1

考虑以下查询,其中两个集合都需要由相同的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 子句。

4

6 回答 6

4

我会将查询重新分解为:

SELECT *
FROM Orders
WHERE Quantity BETWEEN 1 AND 100
AND Quantity NOT BETWEEN 50 AND 75
AND Location = 'SE';
于 2012-08-10T02:32:38.923 回答
1

您可以使用 AND NOT 代替 EXCEPT [ 1 ] 来处理集合操作,在不同平台上获得更大的支持。

我觉得有一点值得一提,总结一下:

  1. 把最不可能的表达放在第一位。
  2. 将最不复杂的表达式放在首位。
  3. 使用更多和更少的搜索。

如果由于从右到左的评估而不是从左到右的评估而使用 Oracle,则颠倒第 1 点和第 2 点。

于 2012-08-10T02:59:34.963 回答
1

You can do this with a 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

If CTEs are not available, you could do the same thing with a view.

于 2012-08-10T02:45:10.573 回答
0
SELECT *
FROM   Orders
WHERE  ((Quantity BETWEEN 1 AND 49) OR (Quantity BETWEEN 76 AND 100))
AND Location = 'SE'

试试这个查询并确保它获取相同的结果。

于 2012-08-10T02:34:02.137 回答
0

我会这样做:

SELECT *
FROM   Orders
WHERE  ((Quantity BETWEEN 1 AND 49)
OR (Quantity BETWEEN 76 AND 100))
AND Location = 'SE';
于 2012-08-10T02:34:16.737 回答
-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)
于 2012-08-10T02:38:21.510 回答