SQL query is very slow in Symfony, but very fast in PhpMyAdmin

I am working on a Business Intelligence application. I am making the following request in the Symfony repository:

public function countSubscribers()
{
    $sql = "SELECT COUNT(DISTINCT(a.id))
    FROM account a
    INNER JOIN customer c ON c.account = a.id
    INNER JOIN payment p ON p.customer = c.id
    WHERE p.init != 1
    AND p.cancel_date IS NULL
    AND p.unpaid != 1
    AND p.abo = 1
    AND p.value != 0
    AND c.date_next_payement > NOW()";

    $connection = $this->getEntityManager()->getConnection();
    $statement = $connection->prepare($sql);
    $statement->execute();
    $result = $statement->fetchColumn();

    return $result;
}

      

The page loads very slowly and, according to the symfony profiler, the request took over 15 seconds:

SELECT COUNT(DISTINCT(a.id)) FROM account a INNER JOIN customer c ON c.account = a.id INNER JOIN payment p ON p.customer = c.id WHERE p.init != 1 AND p.cancel_date IS NULL AND p.unpaid != 1 AND p.abo = 1 AND p.value != 0 AND c.date_next_payement > NOW() Parameters: { }
[Hide runnable query]
Time: 14553.83 ms [ - Explain query ]
Explanation:
id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
1   SIMPLE  c   ALL     PRIMARY,UNIQ_81398E097D3656A4               179226  Using where
1   SIMPLE  a   eq_ref  PRIMARY     PRIMARY     8   evotest.c.account   1   Using index
1   SIMPLE  p   ref     IDX_6D28840D81398E09    IDX_6D28840D81398E09    9   evotest.c.id    1   Using where

      

So, I tried to run this request in PhpMyAdmin and the request takes less than 1 second. Any idea why such a difference? My webpage is doing a bunch of other requests, but this is the request that uses almost all of the total load time.

UPDATED REQUEST:

SELECT COUNT(DISTINCT(c.id)) 
FROM customer c 
INNER JOIN payment p ON p.customer = c.id 
WHERE p.init != 1 
AND p.cancel_date IS NULL 
AND p.unpaid != 1 
AND p.abo = 1 
AND p.value != 0 
AND c.date_next_payement > NOW()

      

This request is still very slow. Is there a way to optimize it? I want to calculate the number of customers who have at least 1 payment with the given filters. the relation is at c.id = p.customer

+3


source to share


1 answer


I would try a subquery with EXISTS

instead of a full join.



SELECT COUNT(1) 
FROM customer c
WHERE c.date_next_payement > NOW()
AND EXISTS (
  SELECT 1
  FROM payment p 
  WHERE p.customer = c.id 
  AND p.init != 1 
  AND p.cancel_date IS NULL 
  AND p.unpaid != 1 
  AND p.abo = 1 
  AND p.value != 0
);

      

0


source







All Articles