Symfony2 QueryBuilder 中带有计数和分组依据的 SQL 查询

2022-01-16 00:00:00 mysql symfony doctrine

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

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

但我想在 Symfony2 中使用 Doctrine 和 createQueryBuilder() 执行此操作.我试过这个,但没有用:

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 :)

推荐答案

你需要运行 2 个查询:

You need to run 2 queries:

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

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

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

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

相关文章