登录
首页 >  Golang >  Go问答

需要将 SQL 查询转换为 Gorm 查询

来源:stackoverflow

时间:2024-02-10 21:18:23 392浏览 收藏

Golang不知道大家是否熟悉?今天我将给大家介绍《需要将 SQL 查询转换为 Gorm 查询》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!

问题内容

我有这个 sql 查询

select concat(kafka_user_stream.firstname,' ', kafka_user_stream.lastname) as "full name", 
kafka_user_stream.uid as "user id", 
kafka_user_stream.countrycode as "country",
kafka_user_stream.createdat as "registration date & time",
count(jackpotmessage_stream.uid) as "win count"
from kafka_user_stream left join 
jackpotmessage_stream on jackpotmessage_stream.uid = kafka_user_stream.uid
where "type"='goldenticketwin' 
group by "full name", "user id", "country", "registration date & time"
order by "win count" desc

我想将其转换为 gorm。我可以使用它

err = s.db.Exec("...QUERY")

但我无法从上述查询中提取数据。我需要提取上述所有字段(全名、用户 id 等)并将它们存储在结构中。

在上面的查询中,kafka_user_stream 和 jackpot_message 是从 kafka 流中提取的表。我正在使用 go-gorm 和 go。

我尝试了 gorm 文档以及其他一些参考资料,但找不到任何解决方案。非常感谢任何线索、见解或帮助。


正确答案


使用本机 go/mysql 驱动程序,您应该使用 query()scan() 方法从数据库获取结果并将其存储在结构中,而不是 exec()

在 gorm 中,您可以使用 SQL Builder 进行自定义查询:

type result struct {
  id   int
  name string
  age  int
}

var result result
db.raw("select id, name, age from users where name = ?", 3).scan(&result)

我按照 aykut 的建议找到了一种稍微不同的方法,效果很好。

rows, _err := s.gdb.Raw(`Select CONCAT(kafka_user_stream.FirstName,' ', kafka_user_stream.LastName) AS "FullName", 
    kafka_user_stream.UID AS "UserID", 
    kafka_user_stream.CountryCode AS "Country",
    kafka_user_stream.CreatedAt AS "CreatedAt",
    COUNT(jackpotmessage_stream.UID) AS "WinCount"
    FROM kafka_user_stream LEFT JOIN 
    jackpotmessage_stream ON jackpotmessage_stream.UID = kafka_user_stream.UID
    WHERE "Type"='goldenTicketWin' 
    GROUP BY "FullName", "UserID", "Country", "CreatedAt"
    ORDER BY "WinCount" DESC;`).Rows()

到这里,我们也就讲完了《需要将 SQL 查询转换为 Gorm 查询》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>