带有 SET 变量语句的 Mysqli 查询(即多个查询)

2021-12-25 00:00:00 sql php mysql mysqli

我想设置一个变量以在 mysqli 查询中使用.这不太行.在 mysqli 之前,我曾经设置查询调用.我玩 db->multi_query($sql) 没有运气.任何人都知道如何使这项工作包括 set 语句?

I want to set a variable to use in a mysqli query. This doesn't quite work. Prior to mysqli I used to set query calls. I played around with db->multi_query($sql) with no luck. Anyone out there have an idea how to make this work including a set statement?

$sql = 'SET @rownum := 0;';
$sql .= 'SELECT @rownum :=@rownum + 1 AS Rank, User_Id, COUNT(User_ID) AS Block_Count
               FROM Block_Owners;

$stmt = $db->prepare($sql);
$stmt->bind_param('ii', $world, $userId);
// execute the query
$stmt->execute();

推荐答案

在两个单独的查询中进行:

Do it in two separate queries:

$db->query('SET @rownum := 0');
$sql = 'SELECT @rownum :=@rownum + 1 AS Rank, User_Id, COUNT(User_ID) AS Block_Count FROM Block_Owners'
$stmt = $db->prepare($sql);
$stmt->bind_param('ii', $world, $userId);
$stmt->execute();

但是请注意,您要运行的查询将始终返回单行(Rank = 1),因为您使用的是没有 GROUP BY 的聚合函数.

Note, however, that the query you want to run will always return a single row (with Rank = 1) since you are using an aggregate function without GROUP BY.

相关文章