SQL 查询产生 SQL 异常,但 运行 它在 DBMS 中没有错误?
SQL query yields an SQL exception, but running it in the DBMS is error-free?
我正在使用 PDO 执行以下 SQL 查询,该查询应该匹配 5
users
与我事先检索到的单个 mod
:
$sql = 'INSERT INTO modusergrade (`ModId`, `UserId`)
SELECT :modId AS ModId, u.Id AS UserId
FROM users AS u
LEFT OUTER JOIN modusergrade AS g ON g.UserId = u.Id
WHERE u.Id NOT IN
(SELECT UserId
FROM moduserconflicts
WHERE ModId = :modId)
GROUP BY u.Id
ORDER BY COUNT(g.ModId), rand()
LIMIT :maxUsers';
$query = $db->prepare($sql);
$query->bindParam(':modId', $id, PDO::PARAM_INT);
$query->bindParam(':maxUsers', $maxUsers, PDO::PARAM_INT);
$query->execute();
但是,执行此操作会产生以下错误:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near "5" at line 11
第 11 行对应于 LIMIT
,因此我假设 rand()
存在某种问题。我是否应该通过其他方式传递它以获得 "order randomly" 效果?
如图所示here 问题在于 pdo 处理此参数化限制的方式。在绑定之前,您需要先将值转换为整数 (int)
。
我正在使用 PDO 执行以下 SQL 查询,该查询应该匹配 5
users
与我事先检索到的单个 mod
:
$sql = 'INSERT INTO modusergrade (`ModId`, `UserId`)
SELECT :modId AS ModId, u.Id AS UserId
FROM users AS u
LEFT OUTER JOIN modusergrade AS g ON g.UserId = u.Id
WHERE u.Id NOT IN
(SELECT UserId
FROM moduserconflicts
WHERE ModId = :modId)
GROUP BY u.Id
ORDER BY COUNT(g.ModId), rand()
LIMIT :maxUsers';
$query = $db->prepare($sql);
$query->bindParam(':modId', $id, PDO::PARAM_INT);
$query->bindParam(':maxUsers', $maxUsers, PDO::PARAM_INT);
$query->execute();
但是,执行此操作会产生以下错误:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near "5" at line 11
第 11 行对应于 LIMIT
,因此我假设 rand()
存在某种问题。我是否应该通过其他方式传递它以获得 "order randomly" 效果?
如图所示here 问题在于 pdo 处理此参数化限制的方式。在绑定之前,您需要先将值转换为整数 (int)
。