ORM组件目前支持常见的三种语法的子查询:Where子查询、Having子查询及From子查询。

Where子查询

我们可以在Where条件中使用子查询语句,示例:

  1. // 获取默认配置的数据库对象(配置名称为"default")
  2. db := g.DB()
  3. db.Model("orders").Where("amount > ?", db.Model("orders").Fields("AVG(amount)")).Scan(&orders)
  4. // SELECT * FROM "orders" WHERE amount > (SELECT AVG(amount) FROM "orders")

Having子查询

我们可以在Having条件中使用子查询语句,示例:

  1. subQuery := db.Model("users").Fields("AVG(age)").WhereLike("name", "name%")
  2. db.Model("users").Fields("AVG(age) as avgage").Group("name").Having("AVG(age) > ?", subQuery).Scan(&results)
  3. // SELECT AVG(age) as avgage FROM `users` GROUP BY `name` HAVING AVG(age) > (SELECT AVG(age) FROM `users` WHERE name LIKE "name%")

From子查询

我们可以在使用Model方法创建模型时使用子查询语句,示例:

  1. db.Model("? as u", db.Model("users").Fields("name", "age")).Where("age", 18).Scan(&users)
  2. // SELECT * FROM (SELECT `name`,`age` FROM `users`) as u WHERE `age` = 18
  3. subQuery1 := db.Model("users").Fields("name")
  4. subQuery2 := db.Model("pets").Fields("name")
  5. db.Model("? as u, ? as p", subQuery1, subQuery2).Scan(&users)
  6. // SELECT * FROM (SELECT `name` FROM `users`) as u, (SELECT `name` FROM `pets`) as p