PHP MySQL - 选择id不等于2个ID中的两个ID

时间:2017-10-13 18:34:42

标签: php sql pdo equals

所以我试图随机选择2行,但不允许id等于x或等于y。

这就是我到目前为止所做的:

  $statment = $db -> "SELECT * FROM player ORDER BY RAND() LIMIT 2 WHERE 
              NOT(id = ?) OR WHERE NOT(id=?)";
  $statement->execute(array($player1, $player2));

但是得到:

  

解析错误:语法错误,意外''SELECT * FROM player ORDER BY'(T_CONSTANT_ENCAPSED_STRING),期待标识符(T_STRING)或变量(T_VARIABLE)

2 个答案:

答案 0 :(得分:3)

您需要127.0.0.1以确保它们与AND不同:

<>

或者检查它是否是WHERE id <> ? AND id <> ? 列表:

IN

我不确定SQL语句的顺序,请尝试:

WHERE id NOT IN(?, ?)

此外,您错过了SELECT * FROM player WHERE id <> ? AND id <> ? ORDER BY RAND() LIMIT 2 之类的内容:

prepare

答案 1 :(得分:-1)

使用NOT IN。您还错过了对prepare()的调用。

$statment = $db ->prepare("SELECT * FROM player
                    WHERE id NOT IN (?, ?)
                    ORDER BY RAND()
                    LIMIT 2");

此外,SELECT语句中的子句顺序为:

SELECT
FROM
JOIN
WHERE
GROUP BY
HAVING
ORDER BY
LIMIT