我有以下代码:
SELECT *
FROM table
WHERE thread = $thread
AND (user != $user1 OR user != $user2)
我希望代码选择包含$ thread的所有行,但用户不是$ user1或$ user2。
我的代码是否正确?或者应该是这样的:
SELECT *
FROM table
WHERE thread = $thread
(AND user != $user1 OR user != $user2)
提前致谢
答案 0 :(得分:3)
使用:
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))
答案 1 :(得分:2)
SELECT *
FROM table
WHERE thread = $thread
AND user != $user1
AND user != $user2
答案 2 :(得分:1)
使用此:
SELECT *
FROM table
WHERE thread = $thread
(AND user != $user1 AND user != $user2)
因为您不希望用户是user1或user2,因此使用'AND'将是适当的选项。
此外,如果$thread
不是整数字段,则需要将其括在引号中,例如:
WHERE thread = '$thread'
答案 3 :(得分:1)
您也可以使用
SELECT *
FROM table
WHERE thread = '$thread'
AND user NOT IN ($user1, $user2)
不知道哪个执行得更快,但这是我的首选方式,因为我更喜欢它的可读性。
答案 4 :(得分:0)
我认为你也应该使用<>而不是!=
所以:
SELECT *
FROM table
WHERE thread = $thread
AND user <> $user1
AND user <> $user2