开发者

postgres syntax question for OR?

开发者 https://www.devze.com 2023-01-01 07:49 出处:网络
The first one below works, but, just wanted to see if there\'s a better way... If I\'m trying to find all records that start with \'C\' with either a flag of 2 or a status of 9, do I need to incorpor

The first one below works, but, just wanted to see if there's a better way...

If I'm trying to find all records that start with 'C' with either a flag of 2 or a status of 9, do I need to incorporate the 'C' criteria twice?

i.e.,

"SELECT * FROM mytable WHERE name like 'C%' AND flag开发者_StackOverflow中文版 = 2 OR name like 'C%' AND status = 9"

Or, is there a way quicker way to write it so that I only need to set 'C%' once?


Logically, AND and OR are distributive to each other, i.e.

a & (b | c) = (a & b) | (a & c)

that means your condition can be rewritten as

name LIKE 'C%' AND (flag = 2 OR status = 9)


OR has lower priority than AND so you need parentheses.

WHERE name LIKE "C%" AND (flag = 2 OR flag = 9)

you can also check for membership of a set of values

... AND flag IN (1, 9)

0

精彩评论

暂无评论...
验证码 换一张
取 消