找回密码
 立即注册
搜索
查看: 366|回复: 1

[gorm] 数据库基础操作

  [复制链接]
发表于 2023-2-6 15:29 | 显示全部楼层 |阅读模式

or 条件
// Struct
db.Where("name='jinzhu'").Or(User{Name:"jinzhu2", Age:18}).Find(&users);
// select * from users where name='jinzhu' or(name='jinzhu2 and age=18);


子查询
子查询可以嵌套在查询中,GORM允许在使用 *gorm.DB对象作为参数时生成子查询
db.Where("amount > (?)", db.Table("orders").Select("AVG(amount)")).Find(&orders)
//select * from "orders" where amount > (select AVG(amount) from "orders");

subQuery := db.Select("AVG(age)").Where("name Like ?", "name%").Table("users")

db.Select("AVG(age) as avgage").Group("name").Having("AVG(age) > (?)", subQuery).Find(&results);

//select avg(age) as avgage from users group by name having avg(age) > (select avg(age) from users where name like "name%")
 楼主| 发表于 2023-2-6 15:46 | 显示全部楼层
构建NOT条件,用法与 Where 类似

db.Not("name = ?", "jinzhu").First(&user)
// select * from users  where not name = "ninzhu" order by id limit 1;

// Not In
db.NotIn(map[string]interface{}{"name":[]string{"jinzhu", "jinzhu2"}}).Find(&users)
// select * from users where name not in ("jinzhu, "jinzhu2");

// Struct
db.Not(User{Name:"jinzhu", Age:18}).First(&user);
// select * from users where name <> "jinzhu"   and age <> 18 order by id limit 1;
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|学习笔记

GMT+8, 2025-1-15 12:21 , Processed in 0.036902 second(s), 13 queries , APCu On.

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表