Reputation: 13
I try to retrieve multiple count in a single query on a single table.
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();
With this action I get this result:
array [
"enabled" => "4"
"disabled" => "4"
"locked" => "4"
]
The result that I expected would be this:
array [
"enabled" => "2"
"disabled" => "1"
"locked" => "1"
]
I get that a simple count of the entire table.
Some body knows how i can make it?
Upvotes: 1
Views: 1264
Reputation: 286
SQL query is wrong. You are doing cross join of three tables, but you want to count rows that satisfy some condition in the table:
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
Upvotes: 2