2017-05-30 49 views
0

https://stackoverflow.com/a/12772507/1507546如何使用MySQL的變量理論

我想通過理論來執行這個查詢,但我發現下面的錯誤

[主義\ DBAL \驅動程序\ PDOException] SQLSTATE [42000 ]:語法錯誤或訪問衝突:1064您的SQL語法錯誤;檢查對應於您MariaDB的服務器版本正確的語法附近 使用「@counter:= 0」手動位於第1行

這裏是我的代碼

$sql = <<<S 
    SET @counter = 0; 
    Select sub.orderid,sub.value,(@counter := @counter +1) as counter 
    FROM 
    (
     select orderid, 
      round(sum(unitprice * quantity),2) as value 
     from order_details 
     group by orderid 
    ) sub 
    order by 2 desc 
    limit 10 
S; 

stmt = $this->_em->getConnection()->prepare($sql); 

$stmt->execute(); 

return $stmt->fetchAll(AbstractQuery::HYDRATE_ARRAY); 
+1

嘗試在其他語句中添加'SET'。大多數SQL API不允許在沒有額外配置的情況下在單個查詢中使用多個語句。 – aynber

+0

對不起,謝謝!你可以發佈你的答案,我會接受它 – smarber

回答

1

大多數SQL API的不要不需要額外配置就可以允許多個語句您需要將它們作爲單獨的語句傳入:

$this->_em->getConnection()->exec("SET @counter = 0"); // May need tweaking, I'm not familiar with Doctrine 
$sql = <<<S 
    Select sub.orderid,sub.value,(@counter := @counter +1) as counter 
    FROM 
    (
     select orderid, 
      round(sum(unitprice * quantity),2) as value 
     from order_details 
     group by orderid 
    ) sub 
    order by 2 desc 
    limit 10 
S; 

stmt = $this->_em->getConnection()->prepare($sql);