使用 Symfony 2 和 Doctrine,我正在寻找一种方法来选择特定列中具有最大值的每一行。
现在,我正在两个查询中执行此操作:
我确信这可以通过一个查询来完成。
搜索中,我发现了这个答案 in a thread,这似乎就是我正在寻找的东西,但是是在 SQL 中。
因此,根据答案的第一个解决方案,我尝试构建的查询将类似于:
select yt.id, yt.rev, yt.contents
from YourTable yt
inner join(
select id, max(rev) rev
from YourTable
group by id
) ss on yt.id = ss.id and yt.rev = ss.rev
有人知道如何在 Doctrine DQL 中实现它吗?
现在,这是我的测试代码(不起作用):
$qb2= $this->createQueryBuilder('ms')
->select('ms, MAX(m.periodeComptable) maxPeriode')
->where('ms.affaire = :affaire')
->setParameter('affaire', $affaire);
$qb = $this->createQueryBuilder('m')
->select('m')
//->where('m.periodeComptable = maxPeriode')
// This is what I thought was the most logical way of doing it:
->innerJoin('GAAffairesBundle:MontantMarche mm, MAX(mm.periodeComptable) maxPeriode', 'mm', 'WITH', 'm.periodeComptable = mm.maxPeriode')
// This is a version trying with another query ($qb2) as subquery, which would be the better way of doing it for me,
// as I am already using this subquery elsewhere
//->innerJoin($qb2->getDQL(), 'sub', 'WITH', 'm.periodeComptable = sub.maxPeriode')
// Another weird try mixing DQL and SQL logic :/
//->innerJoin('SELECT MontantMarche mm, MAX(mm.periodeComptable) maxPeriode ON m.periodeComptable = mm.maxPeriode', 'sub')
//->groupBy('m')
->andWhere('m.affaire = :affaire')
->setParameter('affaire', $affaire);
return $qb->getQuery()->getResult();
实体是 GAAffairesBundle:MontantMarche,因此此代码位于相应存储库的方法中。
更一般地说,我正在学习如何处理高级查询的子查询(SQL 和 DQL)以及 DQL 语法。
Thx!