go - Go的sqlc支持join吗?

标签 go sqlc

我正在阅读 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

Embedding allows you to reuse existing model structs in more queries, resulting in less manual serialization work. First, imagine we have the following schema with students and test scores.

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
);

We want to select the student record and the scores they got on a test. Here's how we'd usually do that:

-- name: ScoreAndTests :many
SELECT students.*, test_scores.*
FROM students
JOIN test_scores ON test_scores.student_id = students.id
WHERE students.id = ?;

When using Go, sqlc will produce a struct like this:

type ScoreAndTestsRow struct {
  ID        int64
  Name      string
  Age       int32
  StudentID int64
  Score     int32
  Grade     string
}

With embedding, the struct will contain a model for both tables instead of a flattened list of columns.

-- 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
}

关于go - Go的sqlc支持join吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66218627/

相关文章:

html - 从 [] 字符串中自动选择 select2

go - 执行大量 I/O 的 go 程序崩溃

go - 如何使用 go build -ldflags 在编译时设置 bool 变量

go - 解码 json 值的更好方法

golang反射初始化满足接口(interface)的结构