【发布时间】:2011-02-08 19:36:04
【问题描述】:
我有一个包含用户名和类别的表,我有查询:
select * from articles where username='333' or username='222' and category='movies'
我希望这仅返回来自“电影”类别的用户“333”和“222”的记录,但这会返回来自所有类别的这些用户的所有文章。
我做错了什么?
【问题讨论】:
标签: sql sql-server-2005 select
我有一个包含用户名和类别的表,我有查询:
select * from articles where username='333' or username='222' and category='movies'
我希望这仅返回来自“电影”类别的用户“333”和“222”的记录,但这会返回来自所有类别的这些用户的所有文章。
我做错了什么?
【问题讨论】:
标签: sql sql-server-2005 select
SELECT *
FROM articles
WHERE (username='333' OR username='222')
AND category='movies'
【讨论】:
select * from articles where (username='333' or username='222') and category='movies'
【讨论】:
使用 IN 关键字代替 AND/OR 可能会有所帮助。
select *
from articles
where username in ('333','222') and category='movies'
IN 允许您指定值列表。
此外,如果您想MIX AND/OR,请确保将它们括起来。如果您不将它们括起来,则大多数主要 RDBMS 中的 优先级 是 OR 之前的 AND(ANDS 周围的括号)。
select *
from articles
where (username = '333' or username = '222') and category='movies'
从这里可以看到(Operator Precedence (TSQL 2005),AND 排在第 7 位,而 OR 排在第 8 位。
【讨论】:
可能你没有括号。如果您更明确,例如:
select * from articles where (username='333' or username='222') and category='movies'
那你应该没事。
还有一个IN 关键字,所以你可以这样做:
select * from articles where username in ('333', '222') and category='movies'
【讨论】:
操作符前置。您可能需要阅读手册。 AND 绑定更紧密(优先级高于)'OR',因此您的查询被解析为
select *
from articles
where username = '333' or ( username = '222' and category = 'movies' )
您需要使用括号来明确指定您想要的操作顺序:
select *
from foo
where ( user = 'a' or user = 'b' )
and category = 'c'
或者,使用in:
select *
from foo
where user in ('a','b')
and category = 'c'
【讨论】:
你期望它被解析:
select * from articles where (username='333' or username='222') and category='movies'
但它被解析:
select * from articles where username='333' or (username='222' and category='movies')
加上括号,它会做正确的事。
【讨论】: