Symfony2 QueryBuilder中带有count和group的SQL查询

时间:2021-10-13 15:45:59

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

我需要你的帮助。我有这个SQL查询:

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 :

但是我想在Symfony2中使用Doctrine和createQueryBuilder()来完成这个。我试试这个,但没有用:

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

Can you help me please ? Thanks :)

你能帮我吗 ?谢谢 :)

3 个解决方案

#1


9  

You need to run 2 queries:

您需要运行2个查询:

$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();

#2


1  

$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

希望它有所帮助,即使它是一个旧堆栈

#3


0  

I tried to use

我试着用

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

and it's seem to work fine so far.

到目前为止似乎工作正常。

#1


9  

You need to run 2 queries:

您需要运行2个查询:

$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();

#2


1  

$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

希望它有所帮助,即使它是一个旧堆栈

#3


0  

I tried to use

我试着用

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

and it's seem to work fine so far.

到目前为止似乎工作正常。