php – 将SQL查询循环合并到一个SQL查询中

我在
PHP中构建了一个循环,可以生成500个SQL查询,但是我想将500个SQL查询合并为一个并获得相同的返回(公司和每个公司的用户数)

PHP代码示例

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

我要合并的2个SQL查询的示例

查询1

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

查询2

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

我更喜欢使用createQueryBuilder http://symfony.com/doc/current/book/doctrine.html#querying-for-objects-using-doctrine-s-query-builder的解决方案,但我也很高兴使用SQL本机查询.

最佳答案 使用条件聚合:

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_ 
点赞