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

Need to convert the SQL Query to Gorm query

我有这个 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 然后继续。

我尝试了 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()