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

Where子查询

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

g.Model("orders").Where("amount > ?", g.Model("orders").Fields("AVG(amount)")).Scan(&orders)
// SELECT * FROM "orders" WHERE amount > (SELECT AVG(amount) FROM "orders")

Having子查询

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

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

From子查询

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

g.Model("? as u", g.Model("users").Fields("name", "age")).Where("age", 18).Scan(&users)
// SELECT * FROM (SELECT `name`,`age` FROM `users`) as u WHERE `age` = 18

subQuery1 := g.Model("users").Fields("name")
subQuery2 := g.Model("pets").Fields("name")
g.Model("? as u, ? as p", subQuery1, subQuery2).Scan(&users)
// SELECT * FROM (SELECT `name` FROM `users`) as u, (SELECT `name` FROM `pets`) as p











Content Menu

  • No labels

8 Comments

  1. xx

    有没EXISTS的子查询?比如像这个查询某日新增付费用户数的sql语句

    SELECT COUNT(1)  FROM payment_order p WHERE created_at between '2021-06-09 00:00:00' and '2021-06-09 23:59:59' AND `status`=1 AND  NOT EXISTS (SELECT DISTINCT uid from payment_order pp WHERE created_at < "2021-06-09 00:00:00" AND p.uid=pp.uid )

    1. 暂时没有快速方法,你可以这样:

      subQuery := g.Model("payment_order", "pp").Distinct().Fields("uid").WhereLT("created_at", "2021-06-09 00:00:00").Where("p.uid", "pp.uid")
      g.Model("payment_order", "p").
      	WhereBetween("created_at", "2021-06-09 00:00:00", "2021-06-09 23:59:59").
      	Where("status", 1).
      	Where("NOT EXISTS ?", subQuery).
      	Count()
      1. xx

        谢谢大佬已经可以了,之前用dao.PaymentOrder.Where一直子查询报错,用g.Model("paument_order",“p”).Where就可以了;

        不过大佬写的WhereLT函数好像1.6还没有

  2. 有没有 AndOr多条件查询的组合查询?

    比如 where (a=1 or b=1) and c= 1 这种,在 Laravel 里面可以用闭包传入 where 实现 ,试了下,没有找到好的解决方案

    写了子查询

    subQuery := g.Model("test").Where("a", 1).WhereOr("b", 1) g.Model("test").Where(subQuery).Where("c", 1)


    实际子查询没有生效

    1. 你可以采用 Wheref 进行格式化查询语句。

      g.Model("user").Wheref("(a=? or b=?)and c=?", 1, 1, 1)
      //SELECT `id`,`name`,`age`,`time` FROM `user` WHERE (a=1 or b=1)and c=1



  3. accessData := g.Model(`Appaccess ac`).
       LeftJoin(`hz_app_list ha`, `ac.dst_ip=ha.Address`).
       Fields(`ha.AppName,ac.proto,ac.dst_port,ac.count,ac.accesstype,ac.dst_ip`).
       WhereIn(`ac.src_ip`, SourceIpList).
       Distinct()
    res, _ := g.Model(`? as aaa`, accessData).
       Fields(`AppName,dst_ip,proto,dst_port,SUM(count) as count,accesstype`).
       Group(`AppName,dst_ip,proto,dst_port,accesstype`).
       All()

    ``

    使用join和from子查询,有报错,但是可以正常返回结果   这是什么原因呢

    2021-12-22 15:08:07.169 [ERRO] [ 49 ms] [default] SHOW FULL COLUMNS FROM
    Error: Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near
     '' at line 1

  4. =============================正确执行不会报错====================================
    fromChild := g.Model("user").Fields("age") // 一个字段的时候
    from, _ := g.Model("? as u", fromChild).Where("age > ?", 20).All()
    2023-02-24 18:31:21.760 [DEBU] {381ba4800ebc46176334be35dd981b7b} [ 45 ms] [default] [memory_kingdom] [rows:11 ] SHOW FULL COLUMNS FROM `user`
    2023-02-24 18:31:21.760 [DEBU] {68cf49830ebc46176434be35d421ae44} [  0 ms] [default] [memory_kingdom] [rows:3  ] SELECT * FROM (SELECT `age` FROM `user`) as u WHERE age > 20
    =============================正确执行不会报错====================================
    
    
    =============================能查询出数据,但是会报错=============================
    fromChild := g.Model("user").Fields("nickname", "age") // 多个列的时候
    from, _ := g.Model("? as u", fromChild).Where("age > ?", 20).All()
    2023-02-24 18:31:47.450 [DEBU] {d05f0c7c14bc46171860f9671c125912} [ 42 ms] [default] [memory_kingdom] [rows:11 ] SHOW FULL COLUMNS FROM `user`
    2023-02-24 18:31:47.452 [ERRO] {a8598d7e14bc46171960f967b3e3bbdf} [  2 ms] [default] [memory_kingdom] [rows:0  ] SHOW FULL COLUMNS FROM `age`
    Error: Error 1146 (42S02): Table 'memory_kingdom.age' doesn't exist
    2023-02-24 18:31:47.453 [DEBU] {90eab47e14bc46171a60f9677250d81d} [  0 ms] [default] [memory_kingdom] [rows:3  ] SELECT * FROM (SELECT `nickname`,`age` FROM `user`) as u WHERE age > 20
    [
        {
            "nickname": "赵六",
            "age":      "21",
        },
        {
            "nickname": "孙七",
            "age":      "22",
        },
        {
            "nickname": "周八",
            "age":      "23",
        },
    ]

    这个"age"表,确实不存在,可为什么要去(SHOW FULL COLUMNS FROM `age`)这个表呢?
    是我什么地方做得不对吗?
    请问,有什么办法可以处理这个问题?
    谢谢~
    =============================能查询出数据,但是会报错=============================

    1. 请使用最新版本尝试,如果问题依旧,请提issue并粘贴可复现代码到github上。