登录
首页 >  Golang >  Go问答

sqlc在Go中是否支持连接操作?

来源:stackoverflow

时间:2024-03-15 10:24:28 324浏览 收藏

一分耕耘,一分收获!既然打开了这篇文章《sqlc在Go中是否支持连接操作?》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!

问题内容

我正在从 https://docs.sqlc.dev/en/latest/howto/query_count.html 阅读 SQLC 文档。我想在我的项目中使用它。但是,我没有看到任何与表上的连接操作相关的文档。在 SQLC 中真的可能吗?如果是,我在哪里可以找到文档或参考资料?


解决方案


像“cdf7025: Add MySQL json test”(或“456fcb1 Add MySQL test for SELECT * JOIN”)这样的提交表明支持连接。

2021:但确实,正如 issue 643 中提到的,使用 join 的查询目前尚未记录在案。

2023 年:现在(2023 年 9 月)相同的 issue 643 包含对新文档的引用(感谢 Kyle Gray):

Embedding structs

嵌入允许您在更多查询中重用现有模型结构,从而产生 减少手动序列化工作。首先,假设我们有以下模式 与学生和考试成绩。

create table students (
  id   bigserial primary key,
  name text not null,
  age  integer not null
);

create table test_scores (
  student_id bigint not null,
  score      integer not null,
  grade      text not null
);

我们想要选择学生记录和他们在测试中获得的分数。 我们通常会这样做:

-- name: scoreandtests :many
select students.*, test_scores.*
from students
join test_scores on test_scores.student_id = students.id
where students.id = ?;

当使用 go 时,sqlc 将生成如下结构:

type scoreandtestsrow struct {
  id        int64
  name      string
  age       int32
  studentid int64
  score     int32
  grade     string
}

通过嵌入,该结构将包含两个表的模型,而不是一个 扁平化的列列表。

-- name: scoreandtests :many
select sqlc.embed(students), sqlc.embed(test_scores)
from students
join test_scores on test_scores.student_id = students.id
where students.id = ?;
type ScoreAndTestsRow struct {
  Student   Student
  TestScore TestScore
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

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