在 Go 中,我编写了一个查询来提供所有数据,但我只想获取 products.id 和 client.id 不同的数据。 我可以写什么明喻查询?
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)
在Go中,当我写“Select Distinct”然后休息查询时,它在Go中无效。所以,我想到了使用“group by”编写查询。在Go中,“group by”语法可以通过“GROUP”语法来使用。所以,最后下面的查询对我来说效果很好。
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)
对于我来说,我使用 gorm 来查询数据库,这是我的 SELECT DISTINCT ON 解决方案
tx := dbRepo.db tx = tx.Model(model.ChatMessage{}).Select(fmt.Sprintf("DISTINCT ON (chat_room_id) %s", fields)).Where(filters.Query(),filters.Values()...)