DQL OneToMany查询和执行平均值

时间:2015-11-26 18:03:07

标签: symfony doctrine dql

实体之间的OneToMany关系:

  • Composer> Soundtrack
  • Soundtrack> SoundtrackRating

我希望按给定的Soundtrack选择每个Composer,并为每个SoundtrackRatings支付Soundtrack的费用。

DQL

SELECT s.name, (SUM(r.rating)/COUNT(r.rating)) AS rating 
FROM Soundtrack AS s 
LEFT JOIN SoundtrackRating AS r 
WHERE s.composer = :composer AND r.soundtrackId = s.id 
GROUP BY s.id 
ORDER BY rating DESC

然后我传递:composer类型Composer的实例:

$em->createQuery($dql)
  ->setParameter('composer', $composer)
  ->getResult();

然而,在查询结果中,无论Soundtrack我作为参数传递,我都会收到所有$composer个条目。唯一的区别是只能平均给定$composer的评分,其余的平均值为0

此查询中的问题在哪里?

1 个答案:

答案 0 :(得分:0)

想出来。从r.soundtrackId = s.id子句中移除WHERE并使用WITH中的LEFT JOIN代替:

SELECT s.name, (SUM(r.rating)/COUNT(r.rating)) AS rating 
FROM Soundtrack AS s 
LEFT JOIN SoundtrackRating AS r WITH r.soundtrackId = s.id
WHERE s.composer = :composer 
GROUP BY s.id 
ORDER BY rating DESC