我尝试在单个表上的单个查询中检索多个计数。
return $this->getEntityManager()->createQuery(
'SELECT COUNT(c1) AS enabled, COUNT(c2) AS disabled, COUNT(c3) AS locked
FROM AcmeUserBundle:User c1, AcmeUserBundle:User c2, AcmeUserBundle:User c3
WHERE c1.enabled = 1
AND c2.enabled = 0
AND c3.locked = 1'
)->getSingleResult();
通过这个动作,我得到了这个结果:
array [
"enabled" => "4"
"disabled" => "4"
"locked" => "4"
]
我期望的结果是:
array [
"enabled" => "2"
"disabled" => "1"
"locked" => "1"
]
我得到了整个表格的简单计数。
有些人知道我能做到吗?
答案 0 :(得分:1)
SQL查询错误。您正在进行三个表的交叉连接,但是您想要计算满足表中某些条件的行:
SELECT SUM(CASE WHEN u.enabled = 1 THEN 1 ELSE 0 END) as enabled,
SUM(CASE WHEN u.enabled = 0 THEN 1 ELSE 0 END) as disabled,
SUM(CASE WHEN u.locked = 1 THEN 1 ELSE 0 END) as locked
FROM AcmeUserBundle:User u