2

I'm trying to query a database to get all initials from a table. In SQL, the query would be:

SELECT SUBSTRING(t.name, 1, 1) AS initial FROM Tool t GROUP BY initial

But using QueryBuilder, I haven't found the way to group by aliases. I've tried:

 $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.

And after half an hour of looking for documentation I'm asking again for help. Is it possible, or should I go to another way ?

4

1 回答 1

2

好吧,

正如这里所解释的,问题来自我原来的 sql。使用 DISTINCT 解决问题:

$q = $this->em->createQueryBuilder()
    ->select('DISTINCT UPPER(SUBSTRING(t.name, 1, 1))')
    ->from('...\Entity\Tool', 't')
    ->orderBy('t.name');

为了更安全,我添加了一个 UPPER。

谢谢阅读!

于 2012-07-13T16:44:24.393 回答