How can I SELECT rows with MAX(Column value) in DQL?

心不动则不痛 提交于 2019-12-11 01:08:44

问题


I can not get this query in a symfony2 project that I have.

My Table:

id  course  datetime    numOrden   
---|-----|------------|--------
1  | 1º  | 04/11/2016 | 1   
2  | 2º  | 04/11/2016 | 2
5  | 3º  | 04/11/2016 | 5  
3  | 4º  | 03/11/2016 | 4   
4  | 5º  | 03/11/2016 | 3 

I need to get the course whose value in the "numOrden" column is the maximum( in this case it would be the 3rd course). For this I have used the following query in Doctrine2:

public function findCourse()
{
    return $this->getEntityManager()->createQuery(
    'SELECT c FROM BackendBundle:Curso c WHERE c.numOrden in (SELECT max(c.numOrden) FROM BackendBundle:Curso )')
    ->getResult();
}

Or

    public function findCourse()
{
    return $this->getEntityManager()->createQuery(
    'SELECT c FROM Bundle:Course c WHERE c.numOrden=(SELECT max(c.numOrden) FROM Bundle:Course )')
    ->getResult();
}

But it shows the following error:

[Syntax Error] line 0, col -1: Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got end of string. (500 Internal Server Error)  

回答1:


Try using another alias in the subselect as:

    public function findCourse()
{
    return $this->getEntityManager()->createQuery(
    'SELECT c FROM Bundle:Course c WHERE c.numOrden=(SELECT max(co.numOrden) FROM Bundle:Course co )')
    ->getResult();
}

Hope this help



来源:https://stackoverflow.com/questions/40678668/how-can-i-select-rows-with-maxcolumn-value-in-dql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!