go-gorm / gorm

The fantastic ORM library for Golang, aims to be developer friendly
https://gorm.io
MIT License
36.66k stars 3.92k forks source link

duplicate join clause when using scan() + count(), find() + count() is normal #7079

Open Cirooo opened 3 months ago

Cirooo commented 3 months ago

Description

        var count int64
    var tempList []int
    test := global.GetTransaction().Table(e.TableName() + " as sr").Joins("left join table_s_m sm on sr.s_id = sm.s_id ")
    err2 := test.Distinct("sr.s_id ").Order("sr.s_id desc").Offset((current - 1) * pageSize).Limit(pageSize).Find(&tempList).Offset(-1).Limit(-1).Count(&count).Error

In the example above, it is Find(), and it's normal, but it fails if I replace it with Scan() and it would be this SQL statement: SELECT COUNT(DISTINCT(sr.s_id)) FROM table_s_r as sr left join table_s_m sm on sr.s_id= sm.s_id left join table_s_m sm on sr.s_id= sm.s_id And you can notice that there's a duplicate 'left join' in it. Then mysql throws an error: [1066] [42000]: Not unique table/alias: 'sm'

github-actions[bot] commented 3 months ago

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.ioSearch Before Asking

prabalbansal6183 commented 1 month ago

yeah i also started facing this same issue after upgrading gorm, it used to work fine before. I am not sure why it's happening but (find + count) works fine while (scan + count) don't. here are my package versions (if of any help):- gorm.io/driver/postgres v1.5.6 gorm.io/gorm v1.25.11

github-actions[bot] commented 2 weeks ago

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.ioSearch Before Asking