使用 GORM 在 GO lang 中处理来自 sql 的多个结果集

Handle multiple resultsets from sql in GO lang using GORM

之前的类似问题可以追溯到2012年,当时没有解决方案,所以我不得不重新提问。

struct type DualTable{
  table1 []Table1
  table2 []Table2
  }

  struct type Table1{
  A string
  B string
  }

  struct type Table2{
  P string
  Q string
  }

  var dualtable []DualTable
  var table1 []Table1
  var table2 []Table2

  func main(){
  //trial 1 :failed as i get only table1 result
  db.Raw("select * from table1 select * from table2").Scan(&table1).Scan(&table2)

    //trial 2 :failed as i get only table2 result
  db.Raw("select * from table2 select * from table1").Scan(&table1).Scan(&table2)

  //trial 3 : failed as got nothing
  db.Raw("select * from table1 select * from table2").Scan(&dualtable)
}

如你所见,我正在尝试做什么。
我正在尝试在 DualTable 结构
中获取两个表的结果 但是只有第一个查询好像是运行.

实际代码由非常长的结构组成并且是机密的,所以我不能post在这里。

您需要在两个单独的请求中完成。

var dualtable DualTable
db.Raw("select * from table1").Find(&dualtable.table1)
db.Raw("select * from table2").Find(&dualtable.table2)

更新:

您还可以将 table1table2 嵌入到一个结构中,并将该结构传递给 Scan:

type DualTable struct {
    Table1 //embedded
    Table2 //embedded
}
var dt []DualTable
db.Raw(/*you query here*/).Scan(&dt)

我想回答我自己的问题,因为我在这里没有找到解决方案,但不知何故找到了这个问题的解决方案,

直到 2016 年你才能做到。

但是这种情况已向 GO 开发人员强调,因为这可能主要发生在执行发出多个结果集的存储过程时。

所有细节在这里: https://go-review.googlesource.com/c/go/+/30592/

简短摘要:查询首先为您提供第一个结果集,您可以从中获取结果。一旦你完成了它。使用

result.NextResultSet()

这将简单地从第一个查询结果集切换到下一个结果集。然后你可以从第二个查询中获取结果。

此外,据我所知,GORM 没有此功能。所以我跳过了使用 GORM ORM。

GORM v1 本身不处理这个问题,但是你可以获取底层的查询结果 *sql.Rows,用 table 调用 db.ScanRows 1,调用 rows.NextResultSet 和db.ScanRows 与 table 2

var table1 []Table1
var table2 []Table2

func main()

    rows, err := db.Raw("select * from table1; select * from table2").Rows()

    err = db.ScanRows(rows, &table1)

    if rows.NextResultSet() {
        err = db.ScanRows(rows, &table2)
    } else {
        //only one result set was returned, handle this case
    }

}