Laravel 3中用户定义的MySQL变量?

时间:2013-05-01 13:35:42

标签: mysql laravel

我想使用用户定义的变量更新一组带有序号的MySQL记录的“等级”。以下查询通过MySQL命令行运行正常:

SET @rank:=0; UPDATE scores SET rank=@rank:=@rank+1 WHERE game_id=4 ORDER BY score DESC

但如果我尝试使用Laravel将其作为Fluent查询运行,则会失败。

DB::query("SET @rank:=0; UPDATE scores SET rank=@rank:=@rank+1 WHERE game_id=4 ORDER BY score DESC");

错误讯息:

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 'UPDATE scores SET rank=@rank:=@rank+1 WHERE game_id=4 ORDER BY' at line 1

SQL: SET @rank:=0; UPDATE scores SET rank=@rank:=@rank+1 WHERE game_id=4 ORDER BY score DESC

Bindings: array (
)

[解决]

DB :: raw()来救援!以下作品:

DB::query(DB::raw("SET @rank:=0"));
DB::query("UPDATE scores SET rank=@rank:=@rank+1 WHERE game_id=4 ORDER BY score DESC");

1 个答案:

答案 0 :(得分:1)

无法在一个查询中执行多个语句。 Laravel在引擎盖下使用PDO来防止这种情况发生。您可以尝试通过2个查询来调用此方法,因为@rank在连接期间应该可用。

DB::query("SET @rank:=0");
DB::query("UPDATE scores SET rank=@rank:=@rank+1 WHERE game_id=? ORDER BY score DESC", array(4));