mysql用户变量三个要素,Laravel 3中的用户定义的MySQL变量?

在Laravel中尝试通过Fluent查询执行包含用户定义变量的多条MySQL语句时遇到了错误。问题在于Laravel的PDO底层库不允许在一个查询中执行多条语句。解决方案是将多条语句分开,分别使用DB::query()来执行。通过DB::raw()可以正确执行设置用户变量的语句,然后单独执行更新排名的语句。
摘要由CSDN通过智能技术生成

I want to update the "rank" for a group of MySQL records with sequential numbers using a user-defined variable. The following query runs fine via the MySQL command line:

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

But if I try and run it as a Fluent query using Laravel, it fails.

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

Error message:

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 (

)

[SOLVED]

DB::raw() to the rescue! The following works:

DB::query(DB::raw("SET @rank:=0"));

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

解决方案

It is not possible to execute multiple statements in one query. Laravel uses PDO under the hood which prevents this. You could attempt to call this over 2 queries instead, since @rank should be available for the duration of the connection.

DB::query("SET @rank:=0");

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值