I want to execute a query like below in golang gorm:
select * from MY_TABLE where MY_FIELD in (select max(MY_FIELD) as MY_FIELD from MY_TABLE group by ANOTHER_FIELD)
Is there a way besides raw query in gorm?
You can do this by building up your query. Check out this example:
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 }
Hope this helps.
you can build raw queries
subQuery := db.Model(Table_Name).Select(field).Group(field).QueryExpr() err := db.Model(TableName).Scan(outPutStructArray).Where("myfiled IN (?)", subQuery).Error
and handle error appropriately
You can do this by building up your query. Check out this example:
Hope this helps.