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

问题描述 投票:0回答:1

以前的类似问题可以追溯到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结构中获取两个表的结果但是似乎只有第一个查询在运行。

实际的代码由非常长的结构组成,并且是机密的,因此我不能在此处发布。

sql-server api go struct gorm
1个回答
0
投票

您将需要在两个单独的请求中执行此操作。

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)
© www.soinside.com 2019 - 2024. All rights reserved.