我想在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
}

希望这可以帮助。

10-02 12:31