简单的sql问题帮助

时间:2011-02-08 19:36:04

标签: sql sql-server-2005 select

我有一个包含用户名和类别的表,我有查询:

select * from articles where username='333' or username='222' and category='movies'

我希望这只返回来自“电影”类别的用户“333”和“222”的记录,但这会返回来自所有类别的用户的所有文章。

我做错了什么?

6 个答案:

答案 0 :(得分:3)

SELECT * 
    FROM articles
    WHERE (username='333' OR username='222')
        AND category='movies'

答案 1 :(得分:3)

select * from articles where (username='333' or username='222') and category='movies'

答案 2 :(得分:3)

使用IN关键字代替AND / OR可能会有所帮助。

select *
from articles
where username in ('333','222') and category='movies'

IN允许您指定值列表。

此外,如果您想 MIX 和/或,请确保将它们括起来。如果不对它们进行括号,则大多数主要RDBMS中的优先级在OR之前为AND(在ANDS周围括号)。

select *
from articles
where (username = '333' or username = '222') and category='movies'

正如您在此处(Operator Precedence (TSQL 2005)所见,AND位于第7位,而OR位于第8位。

答案 3 :(得分:2)

可能你没有括号。如果你更明确,比如:

select * from articles where (username='333' or username='222') and category='movies'

然后你应该没事。

还有一个IN关键字,您可以这样做:

select * from articles where username in ('333', '222') and category='movies'

答案 4 :(得分:2)

操作员程序。您可能需要阅读本手册。 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'

答案 5 :(得分:0)

您希望对其进行解析:

select * from articles where (username='333' or username='222') and category='movies'

但是它被解析了:

select * from articles where username='333' or (username='222' and category='movies')

加上括号,它会做正确的事。

相关问题