Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 从左连接的结果创建嵌套结构-您将如何改进我的方法?_Sql_Go_Sqlx - Fatal编程技术网

Sql 从左连接的结果创建嵌套结构-您将如何改进我的方法?

Sql 从左连接的结果创建嵌套结构-您将如何改进我的方法?,sql,go,sqlx,Sql,Go,Sqlx,我从左连接的结果中创建嵌套结构-您如何改进我的代码/使其更具习惯性 使用Scan会导致nil指针值出现问题,我希望避免在结构中使用指针纯粹作为左连接的解决方案 我可以使用reflect包而不是手动将列映射到结构吗 rows, err := db.Queryx(`SELECT category.id, category.parentId, category.name, category.createdAt, category.updatedAt, item.id, item.categoryId,

我从左连接的结果中创建嵌套结构-您如何改进我的代码/使其更具习惯性

使用Scan会导致nil指针值出现问题,我希望避免在结构中使用指针纯粹作为左连接的解决方案

我可以使用reflect包而不是手动将列映射到结构吗

rows, err := db.Queryx(`SELECT
category.id, category.parentId, category.name, category.createdAt, category.updatedAt,
item.id, item.categoryId, item.name, item.createdAt, item.updatedAt
FROM category
LEFT JOIN item ON item.categoryId=category.id
ORDER BY category.id ASC`)
if err != nil {
    return nil, errors.Wrap(err, "Failed to exec category select with items")
}
results := []*CategoryWithItems{}
var prevID int64
var c *CategoryWithItems
for rows.Next() {
    row, err := rows.SliceScan()
    if err != nil {
        return nil, errors.Wrap(err, "Failed to execute SliceScan")
    }
    categoryID := row[0].(int64)
    if prevID == 0 || categoryID != prevID {
        c = &CategoryWithItems{
            Category:Category{
                ID:        categoryID,
                ParentID:  row[1].(int64),
                Name:      string(row[2].([]uint8)),
                CreatedAt: row[3].(time.Time),
                UpdatedAt: row[4].(time.Time),
            },
            Items: []*Item{},
        }
        results = append(results, c)
        prevID = categoryID
    }
    if row[5] != nil {
        i := &Item{
            ID:         row[5].(int64),
            CategoryID: row[6].(int64),
            Name:       string(row[7].([]uint8)),
            CreatedAt:  row[8].(time.Time),
            UpdatedAt:  row[9].(time.Time),
        }
        c.Items = append(c.Items, i)
    }
}