简体   繁体   English

如何使用 GORM 获得不同的结果

[英]How to get distinct results using GORM

In Go, I write a query that gives me all data but I just want to data where products.id and clients.id are distinct.在 Go 中,我编写了一个查询,它提供了所有数据,但我只想提供 products.id 和 clients.id 不同的数据。 What is the simile query I can write?我可以写什么明喻查询?

res := find.Model(&domain.Clients{}).
    Select ("products.id product_id, products.name product_name,"+
        " clients.id id, clients.name name, clients.logo, clients.address, "+
        "clients.business_id, clients.num_of_employee, clients.email, clients.sns_link, clients.phone").
    Joins("LEFT JOIN company_interests ON company_interests.client_id = clients.id").
    Joins("LEFT JOIN products ON products.id = company_interests.product_id").
    Where("products.id = ? ", productId).Find(&resp)

In Go when i write "Select Distinct" then rest query, it is not valid in go.在 Go 中,当我写“选择不同”然后 rest 查询时,它在 go 中无效。 So, i got an idea to write the query using "group by".所以,我想到了使用“group by”编写查询。 In Go "group by" syntax can be used by "GROUP" syntax.在 Go 中,“GROUP”语法可以使用“group by”语法。 So, finally bellow query works fine for me.所以,最后波纹管查询对我来说很好。

res := find.Model(&domain.Clients{}).
    Select ("products.id product_id, products.name product_name,"+
        " clients.id id, clients.name name, clients.logo, clients.address, "+
        "clients.business_id, clients.num_of_employee, clients.email, clients.sns_link, clients.phone").
    Joins("LEFT JOIN company_interests ON company_interests.client_id = clients.id").
    Joins("LEFT JOIN products ON products.id = company_interests.product_id").
    Where("products.id = ? ", productId).
    Group("company_interests.client_id, company_interests.product_id" ).Find(&resp)

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

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