mirror of
https://github.com/ent/ent.git
synced 2026-05-24 09:31:56 +03:00
doc/website: add docs for HAVING + GROUP BY clause (#2326)
* Add docs for HAVING + GROUP BY clause Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com> * Make review changes for docs Signed-off-by: Shivam Sandbhor <shivam.sandbhor@gmail.com>
This commit is contained in:
@@ -84,4 +84,57 @@ func Do(ctx context.Context, client *ent.Client) {
|
|||||||
}).
|
}).
|
||||||
Scan(ctx, &users)
|
Scan(ctx, &users)
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Having + Group By
|
||||||
|
|
||||||
|
This example requires custom SQL modifiers. See how to enable them [here](https://entgo.io/docs/feature-flags/#custom-sql-modifiers)
|
||||||
|
|
||||||
|
In this example we're going to query the oldest users for each role.
|
||||||
|
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"log"
|
||||||
|
|
||||||
|
"entgo.io/ent/dialect/sql"
|
||||||
|
"<project>/ent"
|
||||||
|
"<project>/ent/user"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Do(ctx context.Context, client *ent.Client) {
|
||||||
|
var users []struct {
|
||||||
|
Id Int
|
||||||
|
Age Int
|
||||||
|
Role string
|
||||||
|
}
|
||||||
|
|
||||||
|
client.User.Query().Modify(
|
||||||
|
func(s *sql.Selector) {
|
||||||
|
s.GroupBy(
|
||||||
|
User.Role,
|
||||||
|
)
|
||||||
|
s.Having(
|
||||||
|
sql.EQ(
|
||||||
|
user.FieldAge,
|
||||||
|
sql.Raw(sql.Max(user.FieldAge)),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
).ScanX(ctx, &users)
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
**Note:** The `sql.Raw` is crucial to have. It tells the predicate that `sql.Max` is not an arguement.
|
||||||
|
|
||||||
|
The above code essentially generates the following SQL query:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT * FROM user
|
||||||
|
GROUP BY user.role
|
||||||
|
HAVING user.age = MAX(user.age) ;
|
||||||
```
|
```
|
||||||
Reference in New Issue
Block a user