我正在尝试查询数据库以从表中获取所有缩写。在 SQL 中,查询将是:
SELECT SUBSTRING(t.name, 1, 1) AS initial FROM Tool t GROUP BY initial
但是使用QueryBuilder,我还没有找到按别名分组的方法。我试过:
$q = $this->em->createQueryBuilder()
->select('SUBSTRING(i.name, 1, 1) AS initial')
->from('...\Entity\Tool', 't')
->groupBy('initial');
Error: 'initial' does not point to a Class.
$q = $this->em->createQueryBuilder()
->select('SUBSTRING(t.name, 1, 1)')
->from('...\Entity\Tool', 't')
->groupBy('SUBSTRING(t.name, 1, 1)');
(t.name, 1, ': Error: Cannot group by undefined identification variable.
在寻找文档半小时后,我再次寻求帮助。有可能吗,还是我应该走另一条路?
最佳答案
好的,
如上所述here ,问题出在我原来的sql上。 使用DISTINCT解决问题:
$q = $this->em->createQueryBuilder()
->select('DISTINCT UPPER(SUBSTRING(t.name, 1, 1))')
->from('...\Entity\Tool', 't')
->orderBy('t.name');
为了更加安全,我添加了 UPPER。
感谢您的阅读!
关于sql - groupBy 在 Doctrine QueryBuilder 中使用别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11474268/