开发者

help with sql query with parentheses

i have following code:

SELECT *
FROM table
WHERE thread = $thread
AND (user != $user1 OR user != $user2)

i开发者_JS百科 want the code to pick all rows that contains $thread BUT the user isn't $user1 or $user2.

is my code correct? or should it be like:

SELECT *
FROM table
WHERE thread = $thread
(AND user != $user1 OR user != $user2)

thanks in advance


Use:

SELECT t.*
  FROM TABLE t
 WHERE t.thread = mysql_real_escape_string($thread)
   AND t.user NOT IN (mysql_real_escape_string($user1), mysql_real_escape_string($user2))

Please use mysql_real_escape_string, or risk SQL injection attacks.


SELECT *
FROM table
WHERE thread = $thread
AND user != $user1
AND user != $user2


Use this:

SELECT *
FROM table
WHERE thread = $thread
(AND user != $user1 AND user != $user2)

Because you don't want if the user is either of user1 or user2, for this reason using 'AND' will be proper option here.

Also if the $thread is not an integer field, you need enclose it in quotes eg:

WHERE thread = '$thread'


You could also use

SELECT *
FROM table
WHERE thread = '$thread'
AND user NOT IN ($user1, $user2)

Don't know which executes faster, but this is my preferred way because I like it's readability better.


I think you should also be using <> instead of !=

So:

SELECT *
FROM table
WHERE thread = $thread
AND user <> $user1
AND user <> $user2
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜