有没有办法在SQL查询中将WHERE和HAVING子句一起OR?

时间:2014-01-03 09:30:50

标签: sql

假设我有一个SQL查询

SELECT Label1, Label2, SUM(number) as MySum
FROM MyTable
GROUP BY Label1, Label2

它给了我一些像

的结果
Label1 | Label2 | MySum 
-------+--------+------
Foo    | Bar    |   100
Foo    | Baz    |  -100
NotFoo | Bar    |   100
NotFoo | Baz    |  -100

我可以使用WHEREHAVING子句来过滤结果

SELECT Label1, Label2, SUM(number) as MySum
FROM MyTable
WHERE Label1 = 'Foo'
GROUP BY Label1, Label2
HAVING MySum > 0

这给了我结果

Label1 | Label2 | MySum 
-------+--------+------
Foo    | Bar    |   100

WHEREHAVING一起隐含AND

是否存在类似

的语法
SELECT Label1, Label2, SUM(number) as MySum
FROM MyTable
WHERE Label1 = 'Foo'
GROUP BY Label1, Label2
OR HAVING MySum > 0

给出结果

Label1 | Label2 | MySum 
-------+--------+------
Foo    | Bar    |   100
Foo    | Baz    |  -100
NotFoo | Bar    |   100

我能做到

SELECT Label1, Label2, SUM(number) as MySum
FROM MyTable
WHERE Label1 = 'Foo'
GROUP BY Label1, Label2

UNION 

SELECT Label1, Label2, SUM(number)
FROM MyTable
GROUP BY Label1, Label2
HAVING MySum > 0

缺点:这可能效率低下,因为数据库必须两次计算Foo | Bar | 100行,发现它是重复的,然后将其丢弃。

我也可以写

SELECT Label1, Label2, SUM(number) as MySum
FROM MyTable
WHERE Label1 = 'Foo'
GROUP BY Label1, Label2

UNION ALL

SELECT Label1, Label2, SUM(number)
FROM MyTable
WHERE Label1 <> 'Foo'
GROUP BY Label1, Label2
HAVING MySum > 0

缺点:乍一看开始变得不那么容易理解(可能是最不利的劣势)。

或者

SELECT Label1, Label2, SUM(number) as MySum
FROM MyTable
GROUP BY Label1, Label2
HAVING MySum > 0
OR Label1 = 'Foo'

缺点:这将使数据库可以完成大量非Foo标签的额外工作。

1 个答案:

答案 0 :(得分:1)

你最后的答案很好:

SELECT Label1, Label2, SUM(number) as MySum
FROM MyTable
GROUP BY Label1, Label2
HAVING MySum > 0
OR Label1 = 'Foo'

您已经说过这里有额外的工作,但事实并非如此,因为您必须进行汇总以找出非MySum>0行的Label1='Foo'以确定是否它们应该被包括在内。