Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query with count and group by in Symfony2 QueryBuilder

I need your help please. I have this SQL query :

SELECT * , COUNT( * ) AS count FROM mytable GROUP BY email ORDER BY id DESC LIMIT 0 , 30

But I would like to do this in Symfony2 with Doctrine and the createQueryBuilder(). I try this, but didn't work :

$db = $this->createQueryBuilder('s');
$db->andWhere('COUNT( * ) AS count');
$db->groupBy('s.email');
$db->orderBy('s.id', 'DESC');

Can you help me please ? Thanks :)

like image 979
13bonobo Avatar asked Jul 14 '13 19:07

13bonobo


3 Answers

You need to run 2 queries:

$db = $this->createQueryBuilder();
$db
    ->select('s')
    ->groupBy('s.email')
    ->orderBy('s.id', 'DESC')
    ->setMaxResults(30);

$qb->getQuery()->getResult();

and

$db = $this->createQueryBuilder();
$db
    ->select('count(s)')
    ->groupBy('s.email')
    //->orderBy('s.id', 'DESC')
    ->setMaxResults(1);

$qb->getQuery()->getSingleScalarResult();
like image 78
Serhii Topolnytskyi Avatar answered Nov 06 '22 12:11

Serhii Topolnytskyi


I tried to use

$query->select('COUNT(DISTINCT u)');

and it's seem to work fine so far.

like image 24
gorodezkiy Avatar answered Nov 06 '22 13:11

gorodezkiy


$db = $this->createQueryBuilder('mytable');
$db
    ->addSelect('COUNT(*) as count')
    ->groupBy('mytable.email')
    ->orderBy('mytable.id', 'DESC')
    ->setFirstResult(0)
    ->setMaxResults(30);
$result = $db->getQuery()->getResult();

Hope it helps even if it's an old stack

like image 2
wasbaiti Avatar answered Nov 06 '22 14:11

wasbaiti