77 lines
2.0 KiB
Go
77 lines
2.0 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
//type User struct {
|
|
// ID uint `gorm:"primaryKey"`
|
|
// Name string `gorm:"size:100"`
|
|
// Email string `gorm:"size:100;unique"`
|
|
// Age int
|
|
// Active bool `gorm:"default:true"`
|
|
// CreatedAt time.Time
|
|
//}
|
|
|
|
func main() {
|
|
db, _ := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
|
|
db.AutoMigrate(&User{})
|
|
|
|
// 插入测试数据
|
|
users := []User{
|
|
{Name: "Alice", Email: "alice@example.com", Age: 30, Active: true},
|
|
{Name: "Bob", Email: "bob@example.com", Age: 25, Active: false},
|
|
{Name: "Charlie", Email: "charlie@example.com", Age: 35, Active: true},
|
|
{Name: "David", Email: "david@example.com", Age: 28, Active: true},
|
|
}
|
|
db.Create(users)
|
|
|
|
// 1. 多条件查询
|
|
var result1 []User
|
|
db.Where("age > ? AND active = ?", 25, true).Find(&result1)
|
|
fmt.Printf("Age > 25 AND active: %d users\n", len(result1))
|
|
|
|
// 2. OR 查询
|
|
var result2 []User
|
|
db.Where("age < ? OR active = ?", 30, false).Find(&result2)
|
|
fmt.Printf("Age < 30 OR inactive: %d users\n", len(result2))
|
|
|
|
// 3. 模糊查询
|
|
var result3 []User
|
|
db.Where("name LIKE ?", "%li%").Find(&result3)
|
|
fmt.Printf("Name contains 'li': %d users\n", len(result3))
|
|
|
|
// 4. 仅查询指定字段
|
|
var result4 []User
|
|
db.Select("name", "email").Find(&result4)
|
|
fmt.Printf("Selected fields: %d users\n", len(result4))
|
|
for _, u := range result4 {
|
|
fmt.Printf(" - %s (%s)\n", u.Name, u.Email)
|
|
}
|
|
|
|
// 5. 统计查询
|
|
var count int64
|
|
db.Model(&User{}).Where("active = ?", true).Count(&count)
|
|
fmt.Printf("Active users count: %d\n", count)
|
|
|
|
// 6. 聚合查询
|
|
var avgAge float64
|
|
db.Model(&User{}).Select("AVG(age)").Row().Scan(&avgAge)
|
|
fmt.Printf("Average age: %.2f\n", avgAge)
|
|
|
|
// 7. 分组查询
|
|
type Result struct {
|
|
Active bool
|
|
Count int64
|
|
}
|
|
var groupResult []Result
|
|
db.Model(&User{}).Select("active, count(*) as count").Group("active").Scan(&groupResult)
|
|
fmt.Println("Group by active:")
|
|
for _, r := range groupResult {
|
|
fmt.Printf(" Active=%v: %d users\n", r.Active, r.Count)
|
|
}
|
|
}
|