gpt4 book ai didi

sql - 如何在golang gorm中执行嵌套查询

转载 作者:IT王子 更新时间:2023-10-29 01:01:48 28 4
gpt4 key购买 nike

我想在 golang gorm 中执行如下查询:

select * from MY_TABLE where MY_FIELD in (select max(MY_FIELD) as MY_FIELD from MY_TABLE group by ANOTHER_FIELD)

除了在 gorm 中进行原始查询,还有其他方法吗?

最佳答案

您可以通过构建查询来做到这一点。看看这个例子:

func FindProspects(categories *string, cities *string, hasEmail *bool, hasContactperson *bool, limit int64, offset int64) []*gModels.Prospect {
var prospects []*gModels.Prospect

query := env.DB().Table("prospects").Select("prospects.id, prospects.name")

if categories != nil {
query = query.Joins("JOIN prospect_categories ON prospect_categories.prospect_id = prospects.id").Where("prospect_categories.category_name IN (?)", strings.Split(*categories, ","))
}

if cities != nil {
query = query.Where("prospects.city IN (?)", strings.Split(*cities, ","))
}

if hasEmail != nil && *hasEmail == true {
query = query.Where("prospects.id IN (SELECT emails.prospect_id FROM emails WHERE emails.prospect_id = prospects.id)")
}

if hasContactperson != nil && *hasContactperson == true {
query = query.Where("prospects.id IN (SELECT contact_people.prospect_id FROM contact_people WHERE contact_people.prospect_id = prospects.id)")
}

query = query.Order("prospects.name ASC")

query.Limit(int(limit)).Offset(int(offset)).Find(&prospects)

return prospects
}

希望这对您有所帮助。

关于sql - 如何在golang gorm中执行嵌套查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41358756/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com