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

时间:2016-04-06 13:13:33

标签: php mysql sql-server symfony

我在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本机查询。

1 个答案:

答案 0 :(得分:1)

使用条件聚合:

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_