1
0
mirror of synced 2024-12-15 23:56:02 +03:00
doctrine2/manual/docs/en/dql-doctrine-query-language/group-by-having-clauses.txt

49 lines
1.3 KiB
Plaintext
Raw Normal View History

2007-11-20 22:22:33 +03:00
DQL GROUP BY syntax:
<code>
GROUP BY groupby_item {, groupby_item}*
</code>
DQL HAVING syntax:
<code>
HAVING conditional_expression
</code>
* GROUP BY and HAVING clauses can be used for dealing with aggregate functions
2007-09-30 00:33:43 +04:00
* Following aggregate functions are available on DQL: COUNT, MAX, MIN, AVG, SUM
Selecting alphabetically first user by name.
2007-09-06 20:31:07 +04:00
<code type="sql">
SELECT MIN(u.name) FROM User u
</code>
Selecting the sum of all Account amounts.
2007-09-06 20:31:07 +04:00
<code type="sql">
SELECT SUM(a.amount) FROM Account a
</code>
* Using an aggregate function in a statement containing no GROUP BY clause, results in grouping on all rows. In the example above we fetch all users and the number of phonenumbers they have.
2007-09-06 20:31:07 +04:00
<code type="sql">
SELECT u.*, COUNT(p.id) FROM User u, u.Phonenumber p GROUP BY u.id
</code>
* The HAVING clause can be used for narrowing the results using aggregate values. In the following example we fetch all users which have atleast 2 phonenumbers
2007-09-06 20:31:07 +04:00
<code type="sql">
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>