views:

231

answers:

2

Hi there, how can i use result of Agregate function in where in Doctrine?

For example i want to know user with silly much numbers.

SELECT  u.name, COUNT(p.id) AS users_phonenumber_count
FROM    users u

    INNER JOIN phonenumbers p ON p.user_id = u.id
WHERE
    users_phonenumber_count > 10
GROUP BY
    u.id

How can i access the *users_phonenumber_count* in where in Dql?

A: 

I can't remember exact details of how I've done this, but remember that it had to use "HAVING"

This is because of the way SQL works, not specifically doctrine - WHERE can't compare computed values, you have to use having (or you could do WHERE COUNT(something) < something )

benlumley
Whatever, but for me is more important how can i access the value. But thank you for your note
Mailo
The point was the you can't access it in WHERE. Not in SQL and not DQL. WHERE filtering happens before GROUP BY, and the aggregated count is only created after the GROUP BY, hence it doesn't exist when the WHERE is applied. You need to use having:GROUP BY u.id HAVING users_phonenumber_count > 10
reko_t
A: 

You need to using HAVING, not WHERE. Also, you need to group by something that's actually in your query, in this case u.name. Assuming u.name is unique - if not, you need to group by both u.id and u.name.

SELECT  u.name, COUNT(*) AS users_phonenumber_count
FROM    users u

    INNER JOIN phonenumbers p ON p.user_id = u.id
GROUP BY
    u.name
HAVING
    count(*) > 10
Magnus Hagander
I was asking for doctrine, but this looks good. I'll try it soon
Mailo
Ah, sorry, missed that :-) Well, that's the kind of SQL you need to come out of the other end of Doctrine :-)
Magnus Hagander
Doctrine DQL supports HAVING... See http://www.doctrine-project.org/documentation/manual/1_0/nl/dql-doctrine-query-language#group-by,-having-clauses
Ropstah