使用Gorm通过原始查询从psql检索sum()结果

huangapple go评论113阅读模式
英文:

Retrieve sum() result from psql using raw query with Gorm

问题

我的原始查询是:

SELECT 
  at."category" AS "category", 
  at."month" AS "month", 
  sum(at.price_aft_discount) as "sum", 
  sum(at.qty_ordered) as "sum2" 
FROM 
  all_trans at 
GROUP BY 
  at."category", 
  at."month" 
ORDER BY 
  at."category" ASC, 
  at."month" ASC

在DBeaver中执行上述查询时,sum列会出现警告:sum: numeric(131089,0) (只读:没有对应的表列)。对于sum2也会出现相同的警告。

我使用Gorm在Go中查询并保存结果的代码如下:

type ATQueryResult struct {
   category string  `gorm:"column:category"`
   month    string  `gorm:"column:month"`
   sum      float32 `gorm:"column:sum"`
   sum2     float32 `gorm:"column:sum2"`
}

queryString := ... // 与上述查询相同
var result []ATQueryResult

db.Table(model.TableAllTrans).Raw(queryString).Find(&result)

fmt.Println(result[3])

但问题是,所有的result[i].sumresult[i].sum2都是0。当我在DBeaver上实时查询时,可以看到实际的非零和数值,尽管会出现上述警告。但是当我尝试将查询结果扫描到result中时,所有的sum值都是0。

英文:

My raw query is

SELECT 
  at."category" AS "category", 
  at."month" AS "month", 
  sum(at.price_aft_discount) as "sum", 
  sum(at.qty_ordered) as "sum2" 
FROM 
  all_trans at 
GROUP BY 
  at."category", 
  at."month" 
ORDER BY 
  at."category" ASC, 
  at."month" asc

When executing above query in DBeaver, the sum columns give warning: sum: numeric(131089,0) (Read-only: No corresponding table column). Same warning is given for sum2

My code to query save the result in Go using Gorm is:

type ATQueryResult struct {
   category string  `gorm:"column:category"`
   month    string  `gorm:"column:month"`
   sum      float32 `gorm:"column:sum"`
   sum2     float32 `gorm:"column:sum2"`
}

queryString := ... // same as above
var result []ATQueryResult

db.Table(model.TableAllTrans).Raw(queryString).Find(&result)

fmt.Println(result[3])

But the issue is, all result[i].sum and result[i].sum2 is 0-zero. I can see the actual sum number (which is all non-zero) when querying live on DBeaver, albeit with the above warning. But when I tried to scan the query result on to result, all the sum values are 0.

答案1

得分: 2

字段必须被导出,以便于gorm(或者它在底层使用的任何东西)能够填充它们。尝试使用以下代码:

type ATQueryResult struct {
    Category string  `gorm:"column:category"`
    Month    string  `gorm:"column:month"`
    Sum      float32 `gorm:"column:sum"`
    Sum2     float32 `gorm:"column:sum2"`
}
英文:

The fields must be exported for gorm (or whatever it leverages under the hood) to be able to populate them. Try using:

type ATQueryResult struct {
	Category string  `gorm:"column:category"`
	Month    string  `gorm:"column:month"`
	Sum      float32 `gorm:"column:sum"`
	Sum2     float32 `gorm:"column:sum2"`
}

huangapple
  • 本文由 发表于 2022年10月27日 16:31:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/74219010.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定