首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Postgresql golang sqlx包查询

Postgresql golang sqlx包查询
EN

Stack Overflow用户
提问于 2021-03-31 22:10:54
回答 2查看 350关注 0票数 0

我使用golang sqlx包和postgresql作为数据库。我有两张简单的桌子

代码语言:javascript
复制
create table items (
    id varchar unique primary key not null,
    is_active bool not null default false
);

create table images (
    item_id varchar not null,
    link varchar unique not null,
    index int not null,
    foreign key (item_id) references items(id) on delete cascade
);

我需要执行的是在一个查询中获得所有已分配图像的项目,之后不再使用go变量进行操作

我有这样的代码来执行该操作

代码语言:javascript
复制
type Image struct {
    ItemID string `db:"item_id" json:"item_id"`
    Index int `db:"index" json:"index"`
    Link string `db:"link" json:"link"`
}

type Images []Image

func (t Images) Value() (driver.Value, error) {
    b, err := json.Marshal(t); if err != nil {
        return driver.Value(""), err
    }
    return driver.Value(string(b)), nil
}

func (t *Images) Scan (src interface{}) error {
    var source []byte

    if reflect.TypeOf(src) == nil {
        return nil
    }

    switch src.(type) {
        case string:
            source = []byte(src.(string))
        case []byte:
            source = src.([]byte)
        default:
            return errors.New("incompatible type for images")
    }

    return json.Unmarshal(source, t)
}

func GetItems (active bool) (items []Item, err error) {
    conn := postgres.Connection()

    const query = `SELECT *, (
        SELECT json_agg(images) AS images FROM (
            SELECT images.link, images.index FROM images GROUP BY images.link, images.index HAVING bool_or(item_id=items.id) AND count(item_id) > 0
        ) as images
    ) FROM items`

    if err := conn.Select(&items, query, active); err != nil {
        logrus.WithError(err).Errorf("Can not get all items")
    }

    return
}

This works but I can have results with items that has no assigned images for them and this code seems tooo complicated for such simple at first sight task. Wish anyone can help me with that
EN

回答 2

Stack Overflow用户

发布于 2021-03-31 22:25:18

如果我没理解错的话,你想这么做:

代码语言:javascript
复制
select i.id 
from images img
join items i 
 on img.item_id = i.id
where i.isactive =1 
group by i.id
票数 0
EN

Stack Overflow用户

发布于 2021-03-31 22:36:28

在@eshirvana的帮助下,我找到了这个解决方案:

代码语言:javascript
复制
SELECT items.*, json_agg(images) as images 
FROM items 
JOIN images 
   ON images.item_id = items.id 
WHERE is_active=$1 
GROUP BY items.id
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66889493

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档