作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我无法在我拥有的 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/
我是一名优秀的程序员,十分优秀!