在我的查询中使用动态SQL时SET赋值(SET @running_total_available:= 0;)在哪里?
我的查询工作正常如图所示,但" @running总计......"当我使用SET @running_total_available:= 0
时崩溃查询并将每一行重置为" 0"不使用SET。
我很难过。谢谢!
$sql = "
SELECT
SQL_CALC_FOUND_ROWS
@running_total_available := 0,
product_source,
username,
product_short_name,
noci_count,
item_listing_id,
IF(num_purchased=0,'', num_purchased) AS num_purchased ,
IF(num_available=0,'', num_available) AS num_available,
IF(num_sold=0,'', num_sold) AS num_sold,
i.tot_items,
date(date_listing_noci) AS date_listing_noci,
IFNULL(date(date_listing_removed),'') AS date_listing_removed,
@running_total_purchased:=@running_total_purchased + i.num_purchased AS running_total_purchased,
@running_total_available:=@running_total_available + i.num_available AS running_total_available,
@running_total_sold:=@running_total_sold + i.num_sold AS running_total_sold,
@running_total_item:=@running_total_item + i.num_sold + i.num_available AS running_total_item,
@running_total_noci:=@running_total_noci + i.noci_count AS running_total_noci
FROM
(SELECT
product_source,
item_listing_id,
p.product_short_name,
username,
noci_count,
IF(num_purchased=0,0,num_purchased) AS num_purchased,
IFNULL(num_available,0) AS num_available,
IFNULL(num_sold,0) AS num_sold,
IFNULL(num_sold,0) + IFNULL(num_available,0) AS tot_items,
date(date_listing_noci) AS date_listing_noci,
IFNULL(date(date_listing_removed),'') AS date_listing_removed
FROM `investigation`
JOIN product p USING (product_id)
WHERE 1 ";
*** dynamic constructs here ***
# close query
$sql.= " ) i ";
$result = $objDbMysqli->query($sql);
答案 0 :(得分:0)
在交叉连接的子查询中初始化它:
SELECT
...
FROM (
...
JOIN product p USING (product_id)
WHERE 1
) i
CROSS JOIN (select @running_total_available := 0) initvars
使用它会自行承担风险,因为无法保证执行顺序。