SQL查询产生SQL异常,但在DBMS中运行它是没有错误的?

时间:2015-03-30 12:31:13

标签: php mysql pdo

我正在使用PDO执行以下SQL查询,该查询应该与5 users匹配,其中mod的ID已经事先检索过:

$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()存在某种问题。我是否应该以其他方式通过它来随机获得"顺序"实现

1 个答案:

答案 0 :(得分:1)

如图here所示,问题在于pdo处理此参数化限制的方式。在绑定之前,您需要先将值转换为Integer (int)