4

I built a loop in PHP that makes 500 SQL queries but I would like to merge the 500 SQL queries into one and get the same return (the companies and the count of the users on each company)

Example of PHP code

$companies =  array();
foreach ($fortune500Service->listAll() as $c ){
  $count = $entityManager
  ->createQueryBuilder()
  ->select("count(u)")
  ->from("AppBundle\Entity\User","u")
  ->where("u.email LIKE :d")
  ->setParameter("d", "%@" . $c["Domain"])
  ->getQuery()->getSingleScalarResult();

  if ($count == 0) {
    continue;
  }

  $companies[] = array(
      "Domain" => $c["Domain"],
      "Company" => "{$c["Company"]} ({$count})",
  );
}
return $companies;

Example of 2 SQL queries that I want to merge

Query 1

SELECT 
  count(u0_.id) 
FROM 
  user u0_ 
WHERE 
  u0_.email LIKE '%@company1.com' 

Query 2

SELECT 
  count(u0_.id)
FROM 
  user u0_ 
WHERE 
  u0_.email LIKE '%@company2.com' 

I prefer a solution using createQueryBuilder http://symfony.com/doc/current/book/doctrine.html#querying-for-objects-using-doctrine-s-query-builder but I am happy also with an SQL native query.

4
  • Put all the u0_.email LIKE '%@somecompany.com' conditions into an array and join them with OR. Commented Apr 6, 2016 at 13:18
  • I am not sure but If I put all the u0_.email LIKE '%@somecompany.com' conditions into an array and join them with OR. The result that I will get is the number of users in any company. For example 4 users in total. I want this result: 2 Users Company1 and 2 Users Company2. Commented Apr 6, 2016 at 13:25
  • Possible dublicate of stackoverflow.com/questions/15230350/… Commented Apr 6, 2016 at 13:27
  • 1
    You could UNION them. Commented Apr 6, 2016 at 13:29

1 Answer 1

1

Use conditional aggregation:

SELECT COUNT(CASE WHEN u0_.email LIKE '%@company1.com' THEN 1 END) as First_cnt,
        COUNT(CASE WHEN u0_.email LIKE '%@company2.com' THEN 1 END) as First_cnt
FROM user u0_ 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.