简体   繁体   English

通过使用 github.com/go-pg/pg 连接两个表来创建更新查询

[英]Create Update query by joining two tables with github.com/go-pg/pg

I am trying to update one field in my postgres table by joining some conditions with another table.我正在尝试通过将某些条件与另一个表连接来更新我的 postgres 表中的一个字段。 I referred this link , which give me a query model that relates to my scenario:我引用了这个链接,它给了我一个与我的场景相关的查询模型:

UPDATE product as p SET price = 200 FROM  product_segment as ps WHERE p.segment_id = ps.id and p.name = 'diam'

Now I have to convert this query in to orm.Query.现在我必须将此查询转换为 orm.Query。 I tried with Join() but it doesn't seem to work .我尝试使用 Join() 但它似乎不起作用。

the code I tried :我试过的代码:

_, err := c.postgresDB.WithContext(ctx).Model(Product).
    Set("price =?", 200).
    Join("LEFT JOIN product_segment as ps").
    JoinOn("ps.id = product.segment_id").
    Where("name =?", "diam").
    Update()

How do I properly write the code to achieve desired result ???如何正确编写代码以达到预期的结果???

After many tries, I ended up doing the below code which gave me the result I wanted.经过多次尝试,我最终完成了下面的代码,这给了我想要的结果。

_, err := c.postgresDB.WithContext(ctx).Model(Product).
    Set("price =? from product_segment as ps", 200).
    Where("name =?", "diam").
    Update()

Please share if you guys have better methods.如果你们有更好的方法,请分享。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM