在Symfony 2.4 Doctrine中获取AVG的最大值

时间:2014-04-23 08:21:07

标签: php sql symfony doctrine-orm symfony-2.4

我需要在symfony doctrine中获得AVG列表的MAX

我的学说查询得到的平均值如下:

SELECT p,AVG(p.pathTime) as avgtime 
FROM ShopperAnalyticsEntityBundle:Path p 
 JOIN p.shopper sh JOIN p.floor f 
 JOIN f.store s 
WHERE p.floor=".$floorId." ".$filter." 
GROUP BY p.xPath, p.yPath

要获取平均值列表的最大值,我将其修改为(在引用this后):

SELECT MAX(avgtime) as maxtime 
FROM (SELECT p,AVG(p.pathTime) as avgtime 
      FROM ShopperAnalyticsEntityBundle:Path p 
       JOIN p.shopper sh 
       JOIN p.floor f 
       JOIN f.store s 
      WHERE p.floor=".$floorId." ".$filter." 
      GROUP BY p.xPath, p.yPath)

我收到以下错误:

[Semantical Error] line 0, col 38 near '(SELECT p,AVG(p.pathTime)': Error: Class '(' is not defined

所以我切换到原生SQL以获得相同的结果:

$maxSQL   = "SELECT MAX(t.avgtime) as maxtime FROM ( SELECT AVG(p.path_time) as avgtime FROM  path p JOIN shopper sh JOIN floor f JOIN store s WHERE p.floor_id=".$floorId." ".$filter." GROUP BY p.x_path, p.y_path ) t ";

$connection = $em->getConnection();
$statement = $connection->prepare($maxSQL);
$statement->execute();
$results = $statement->fetchAll();

我得到了结果,但SQL需要23.4457秒才能运行

任何人都可以在Doctrine中提出一个简单的方法来解决这个问题。

1 个答案:

答案 0 :(得分:0)

你应该这样使用学说:

$query = Doctrine_Query::create()
  ->select('MAX(avgtime) as maxtime ')
  ->from('(SELECT p,AVG(p.pathTime) as avgtime 
           FROM ShopperAnalyticsEntityBundle:Path p 
           JOIN p.shopper sh 
           JOIN p.floor f 
           JOIN f.store s 
           WHERE p.floor=".$floorId." ".$filter." 
           GROUP BY p.xPath, p.yPath)
        ')
  ->execute();

你是怎么做到的?