Gorm: DISTINCT in Count()

Created on 18 Feb 2016  路  2Comments  路  Source: go-gorm/gorm

I need this dynamically generated query:

SELECT count(*) FROM "event" inner join team on team.id = event.team1_id OR team.id = event.team2_id inner join league on league.id = team.league_id

But currently, I think this is not possible.

It's possible to use DISTINCT in Select(): Db.Select("DISTINCT \"event\".*") but currently not possible when using Count()

I'm dynamically generating this query: SELECT DISTINCT "event".* FROM "event" inner join team on team.id = event.team1_id OR team.id = event.team2_id inner join league on league.id = team.league_id LIMIT 10 OFFSET 0 using Gorm's Select(), Where() etc... but I also need the count of all the results w/o using LIMIT 10 OFFSET 0 for pagination purposes.

So what I was trying to do was:

// use Select("DISTINCT \"event\".*"), Preload(), Joins(), Where etc... here...

// then

query.Find(&events).Count(&totalCount)
query.Limit(limit).Offset(offset).Find(&events)

But the count is wrong because this is the query that is being generated by gorm:

SELECT count(*) FROM "event" inner join team on team.id = event.team1_id OR team.id = event.team2_id inner join league on league.id = team.league_id

It's ignoring the Select("DISTINCT \"event\".*")

Note: I can't just easily use a raw query for the count because as I said, the query is dynamically generated, it might contain multiple WHERE clauses etc...

Most helpful comment

@jinzhu Hi, The docs is now moved in http://jinzhu.me/gorm

Where can I find it? And are there any examples that I can use as a reference? Thanks.

All 2 comments

You could use Select and Row, refer: https://github.com/jinzhu/gorm#row--rows

@jinzhu Hi, The docs is now moved in http://jinzhu.me/gorm

Where can I find it? And are there any examples that I can use as a reference? Thanks.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

easonlin404 picture easonlin404  路  3Comments

bramp picture bramp  路  3Comments

superwf picture superwf  路  3Comments

sredxny picture sredxny  路  3Comments

leebrooks0 picture leebrooks0  路  3Comments