gpt4 book ai didi

mysql - 如何在DQL中使用GROUP BY获取每个组中的最新记录?

转载 作者:行者123 更新时间:2023-11-29 11:00:53 24 4
gpt4 key购买 nike

我无法在我拥有的 symfony2 项目中获取此查询。

我的表格:Case_file

id  id_student  last_course  Academic_year  
---|----------|------------|--------------
1 | 1 | 1º Primary | 2014 / 2015
2 | 2 | 2º Primary | 2014 / 2015
5 | 3 | 1º Primary | 2014 / 2015
3 | 1 | 2º Primary | 2015 / 2016
4 | 2 | 3º Primary | 2015 / 2016

我需要根据学年获取每个学生的最后记录。

通过以下查询,我获取每个学生找到的第一行:

public function findOldEstudent()
{

return $this->getEntityManager()->createQuery(
'SELECT c FROM BackendBundle:case_file c INNER JOIN c.student s WHERE s.active=0 GROUP BY s.id ')
->getResult();
}

我的解决方案如下表所示:

id  id_student  last_course  Academic_year  
---|----------|------------|--------------
1 | 1 | 1º Primary | 2014 / 2015 *
2 | 2 | 2º Primary | 2014 / 2015 *
3 | 3 | 1º Primary | 2014 / 2015

而我想要的是根据学年获取最后一行,如下表所示:

id  id_student  last_course  Academic_year  
---|----------|------------|--------------
1 | 1 | 2º Primary | 2015 / 2016 *
2 | 2 | 3º Primary | 2015 / 2016 *
3 | 3 | 1º Primary | 2014 / 2015

为此,我尝试在以下查询中使用 ORDER BY 对行进行排序,但它继续返回找到的第一行:

public function findOldEstudent()
{

return $this->getEntityManager()->createQuery(
'SELECT c FROM BackendBundle:case_file c INNER JOIN c.student s WHERE s.active=0 GROUP BY s.id ORDER BY c.academic_year DESC')
->getResult();
}

感谢您的帮助。

最佳答案

我终于通过以下查询解决了问题:

public function findOldEstudent()
{

return $this->getEntityManager()->createQuery(
'SELECT c FROM BackendBundle:case_file c INNER JOIN c.student s WHERE c.academic_year IN (select MAX(ca.academic_year) FROM BackendBundle:case_file ca INNER JOIN ca.student st GROUP BY st.id) and s.active=0')
->getResult();
}

我遇到的问题是我在子选择中使用了相同的别名,就像在另一个类似的情况下发生的那样 here我不记得了。

希望有帮助。

关于mysql - 如何在DQL中使用GROUP BY获取每个组中的最新记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42282603/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com