DQL (Doctrine Query Language) - GROUP BY, HAVING clauses.php 1.15 KB
Newer Older
hansbrix's avatar
hansbrix committed
1

2
*  GROUP BY and HAVING clauses can be used for dealing with aggregate functions
hansbrix's avatar
hansbrix committed
3 4


5
*  Following aggregate functions are availible on DQL: COUNT, MAX, MIN, AVG, SUM
hansbrix's avatar
hansbrix committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19


Selecting alphabetically first user by name.
<code>
SELECT MIN(u.name) FROM User u
</code>

Selecting the sum of all Account amounts.
<code>
SELECT SUM(a.amount) FROM Account a
</code>



20
*  Using an aggregate function in a statement containing no GROUP BY clause, results in grouping on all rows. In the example above 
hansbrix's avatar
hansbrix committed
21 22 23 24 25 26 27 28
we fetch all users and the number of phonenumbers they have.

<code>
SELECT u.*, COUNT(p.id) FROM User u, u.Phonenumber p GROUP BY u.id
</code>



29
*  The HAVING clause can be used for narrowing the results using aggregate values. In the following example we fetch
hansbrix's avatar
hansbrix committed
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
all users which have atleast 2 phonenumbers
<code>
SELECT u.* FROM User u, u.Phonenumber p HAVING COUNT(p.id) >= 2
</code>




<code type="php">

// retrieve all users and the phonenumber count for each user

$users = $conn->query("SELECT u.*, COUNT(p.id) count FROM User u, u.Phonenumber p GROUP BY u.id");

foreach($users as $user) {
    print $user->name . ' has ' . $user->Phonenumber[0]->count . ' phonenumbers';
}
</code>