Question

How could I count rows in a query with a HAVING clause?

I have a query to fetch paginated data like below (but little more complicated):

$qb = $this->em->createQueryBuilder()
    ->select('p')
    ->from('Application\Entity\Modules_ProductVersions', 'p', 'p.id')
    ->leftJoin('p.stocks', 's')
    ->groupBy('p.id')
    ->having('SUM(s.stock) > 0');
$qb->setMaxResults($limit)
    ->setFirstResult($page * $limit);

I want to additionally count rows, sth like:(althought that triggers Error: Class '(' is not defined):

SELECT COUNT(x) FROM (
SELECT p.id
FROM Application\Entity\Modules_ProductVersions p
LEFT JOIN p.stocks s
GROUP BY p.id
HAVING SUM(s.stock) > 0
) x

How to easily do that using already builded query?

I've managed that using generated SQL:

foreach($query->getParameters() as $param) {
    $params[] = $param->getValue();
};
$count = $this->em->getConnection()->fetchColumn(
    'SELECT COUNT(i) FROM ('.$query->getSQL().') i',
    $params
);

But I would prefer some QueryBuilder or at least DQL method.

Was it helpful?

Solution

Try this one:

SELECT count(p1.*) 
FROM Application\Entity\Modules_ProductVersions p1 
WHERE p1.id IN (
    SELECT p.id
    FROM Application\Entity\Modules_ProductVersions p
    LEFT JOIN p.stocks s
    GROUP BY p.id
    HAVING SUM(s.stock) > 0
);

OTHER TIPS

Using suggested by Refał IN clause, I've managed to do that in QueryBuilder:

$count = $this->em->createQueryBuilder()
    ->select('COUNT(x)')
    ->from('Application\Entity\Modules_ProductVersions', 'x')
    ->where($qb->expr()->in('x.id', $qb->getDQL()))
    ->setParameters($qb->getParameters())
    ->getQuery()->getSingleScalarResult();

Could it be simplified?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top