Doctrine2 - 需要一些帮助来修改工作dql

时间:2013-06-12 20:51:35

标签: symfony doctrine-orm dql

我有以下dql SELECT查询,它可以工作:

SELECT q AS question, AVG(r.score) AS average
  FROM MyBundle:Question q
  JOIN q.ratings r
  WHERE q.deleted IS NULL
  GROUP BY q.id
  ORDER BY q.id ASC

我想做的是,如果AVG(r.score)为0或null,则返回0。我只是不确定该怎么做。是否可以做类似的事情:

SELECT q AS question, (AVG(r.score) OR 0) AS average FROM....

3 个答案:

答案 0 :(得分:2)

由于您无法在WHERE子句中使用聚合函数,因此必须使用HAVING。这应该是诀窍:

SELECT q AS question, AVG(r.score) AS average
  FROM MyBundle:Question q
  JOIN q.ratings r
  WHERE q.deleted IS NULL
  GROUP BY q.id
  HAVING average IN (0, NULL)
  ORDER BY q.id ASC

答案 1 :(得分:0)

您是否正在为doctrine查询构建器寻找mysql IFNULL的替代方案。看看这个question

答案 2 :(得分:0)

将我的(INNER)JOIN改为LEFT OUTER JOIN给了我正在寻找的结果。