登录
首页 >  Golang >  Go问答

使用 Golang 实现左连接并将结果映射到结构

来源:stackoverflow

时间:2024-03-15 18:36:30 412浏览 收藏

在 Golang 中,可以通过使用 left join 查询来连接两个表,并使用自定义实现将结果映射到结构中。通过将 struct1 映射到一个 map,然后遍历所有行,并将 struct2 内容附加到已添加到 map 的 struct1 上,可以将查询结果转换为 struct1 和 struct2 之间的一对多关系。此方法允许将行有效地转换为一个结构数组,其中每个 struct1 具有与之关联的 struct2 数组。

问题内容

我在 go 上有以下结构:

type struct1 struct {
    id          int64    `db:id`
    internalid  int64    `db:internal_id`
    structs2    []struct2
}
type struct2 struct {
   id          int64    `db:id`
   internalid  int64    `db:internal_id`
   sometext    string   `db:some_text`
}

两者的关系是:struct1只能有一个,通过internal_id连接到n个struct2。所以我正在做这个查询:

SELECT*
FROM struct1 st1
LEFT JOIN struct2 st2 
ON
    st1.internal_id = st2.internal_id 
LIMIT 10
OFFSET (1 - 1) * 10;

通过在 go 上执行此查询,我想知道是否可以:通过正确映射数组 struct2 来创建 struct1 数组。如果可以的话我该怎么做?提前致谢。

我正在使用 postgres 和 sqlx。


正确答案


这完全取决于您用来连接数据库的库/客户端,但是,我从未见过库支持您想要执行的操作,因此我将提供您可以执行的自定义实现。完全公开,我没有对此进行测试,但我希望它能为您提供总体思路,任何人都可以随意添加编辑。

package main

type Struct1 struct {
    ID          int64    `db:id`
    InternalID  int64    `db:internal_id`
    Structs2    []Struct2
}

type Struct2 struct {
    ID          int64    `db:id`
    InternalID  int64    `db:internal_id`
    SomeText    string   `db:some_text`
}

type Row struct {
    Struct1
    Struct2
}

func main() {
    var rows []*Row
    // decode the response into the rows variable using whatever SQL client you use

    // We'll group the struct1s into a map, then iterate over all the rows, taking the
    // struct2 contents off of rows we've already added to the map and then appending
    // the struct2 to them. This effectively turns rows into one-to-many relationships
    // between struct1 and struct2.
    mapped := map[int64]*Struct1{}
    for _, r := range rows {
        // The key of the map is going to be the internal ID of struct1 (that's the ONE
        // in the one-to-many relationship)
        if _, ok := mapped[r.Struct1.InternalID]; ok {
            // Make sure to initialize the key if this is the first row with struct1's
            // internal ID.
            mapped[r.Struct1.InternalID] = &r.Struct1
        }
        // Append the struct 2 (the MANY in the one-to-many relationship) to the struct1s
        // array of struct2s.
        mapped[r.Struct1.InternalID].Structs2 = append(mapped[r.Struct1.InternalID].Structs2, r.Struct2)
    }

    // Then convert it to a slice if needed
    results := make([]*Struct1, len(mapped))
    i := 0
    for _, v := range mapped {
        results[i] = v
        i++
    }
}

以上就是《使用 Golang 实现左连接并将结果映射到结构》的详细内容,更多关于的资料请关注golang学习网公众号!

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