DQL OneToMany 查询和执行平均
DQL OneToMany query and performing average
在实体之间的 OneToMany
关系中:
Composer
> Soundtrack
Soundtrack
> SoundtrackRating
我想 select 每个 Soundtrack
一个给定的 Composer
并为每个 Soundtrack
.
平均 SoundtrackRatings
在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
。
这个查询哪里有问题?
想通了。从 WHERE
子句中删除 r.soundtrackId = s.id
并在 LEFT JOIN
中使用 WITH
代替:
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
在实体之间的 OneToMany
关系中:
Composer
>Soundtrack
Soundtrack
>SoundtrackRating
我想 select 每个 Soundtrack
一个给定的 Composer
并为每个 Soundtrack
.
SoundtrackRatings
在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
。
这个查询哪里有问题?
想通了。从 WHERE
子句中删除 r.soundtrackId = s.id
并在 LEFT JOIN
中使用 WITH
代替:
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