Mysqli排名语法

时间:2013-06-05 08:07:24

标签: mysql mysqli

我遇到了mysqli的问题。当我尝试在php中使用它时,我给出了一个错误,但是当我在某些database application中执行查询时,它完美地运行了。它为

提供了错误
SET @rank=0; SELECT (@rank := @rank+1)

我可以在mysql yog中执行正确。有什么替代方法我可以让它运作吗?

以下是代码:

function get_rank($branch,$cat){
    global $connection;
    $result = array();
    $rank = 0;
    if ($statement = $connection->prepare("SET @rank=0; SELECT (@rank := @rank+1) AS rank, a.branch_code_id, SUM(b.amount), c.category FROM sales_add_h AS a INNER JOIN sales_add_i AS b ON a.id = b.sales_h_id INNER JOIN control_panel_item_create AS c ON b.item_code_id = c.id WHERE a.branch_code_id = ? AND c.category = ? GROUP BY c.category, a.branch_code_id, b.amount ORDER BY SUM(b.amount) DESC")) {        
       $statement->bind_param("is",$branch,$cat); 
       $statement->execute();
       $statement->bind_result($a,$b,$c,$d);
        while ($row = $statement->fetch()) {
            array_push($result,array($a,$b,$c,$d));
        }     
        $statement->close();
    } else  {
        printf("Errormessage: %s\n", $connection->error);
        echo " error in SQL Statement.";
    }
    return $result;
}

2 个答案:

答案 0 :(得分:1)

您正在对您的代码执行2次查询,但这不适用于该PHP函数。但您可以将set整合到select

SELECT (@rank := @rank+1) AS rank, a.branch_code_id, SUM(b.amount), c.category 
FROM sales_add_h AS a, 
     (select @rank := 0) r 
INNER JOIN sales_add_i AS b ON a.id = b.sales_h_id 
INNER JOIN control_panel_item_create AS c ON b.item_code_id = c.id
WHERE a.branch_code_id = ? 
AND c.category = ? 
GROUP BY c.category, a.branch_code_id, b.amount 
ORDER BY SUM(b.amount) DESC

答案 1 :(得分:0)

继续我的评论,请尝试使用SQL

SELECT (@rank := @rank+1) AS rank, a.branch_code_id, SUM(b.amount), c.category 
FROM sales_add_h AS a 
INNER JOIN sales_add_i AS b ON a.id = b.sales_h_id 
INNER JOIN control_panel_item_create AS c ON b.item_code_id = c.id 
CROSS JOIN (SELECT @rank=0 ) Sub1
WHERE a.branch_code_id = ? 
AND c.category = ? 
GROUP BY c.category, a.branch_code_id, b.amount 
ORDER BY SUM(b.amount) DESC