Your Question
Title: Inconsistent Behavior of Distinct
with and without Parameters in GORM
Description:
I've noticed some inconsistent behavior when using the Distinct
method in GORM. According to the official documentation, Distinct
should take the fields to be used for distinct selection as parameters. For example:
db.Distinct("name", "age").Order("name, age desc").Find(&results)
However, I have observed the following behavior:
- If I call
Distinct()
without any parameters beforeSelect(...)
, and do not addDistinct
in theSelect(...)
method, it still achieves the distinct effect. - Conversely, if I add
Distinct
in theSelect(...)
method, I must include the same fields in theDistinct
call to achieve the desired effect. If the fields inDistinct
do not match those inSelect
, the distinct effect does not work.
Here is an example to illustrate:
// This works and achieves distinct results
var RuleList []biz.RuleDetailInfo
err := queryCondition.Select(blackWhiteDetailQuery.ALL, blackWhiteQuery.EntityIdentType, blackWhiteQuery.SourcePlatform).
Distinct(blackWhiteDetailQuery.ALL, blackWhiteQuery.EntityIdentType, blackWhiteQuery.SourcePlatform).
Scan(&RuleList)
queryCondition.Distinct().Order("id desc")
var RuleList []biz.RuleDetailInfo
err := queryCondition.Select(blackWhiteDetailQuery.ALL, blackWhiteQuery.EntityIdentType, blackWhiteQuery.SourcePlatform).
Scan(&RuleList)
queryCondition.Distinct(blackWhiteDetailQuery.ID).Order("id desc")
var RuleList []biz.RuleDetailInfo
err := queryCondition.Select(blackWhiteDetailQuery.ALL, blackWhiteQuery.EntityIdentType, blackWhiteQuery.SourcePlatform).
Scan(&RuleList)
// This does not work if fields in Distinct do not match Select
var RuleList []biz.RuleDetailInfo
err := queryCondition.Select(blackWhiteDetailQuery.ALL, blackWhiteQuery.EntityIdentType, blackWhiteQuery.SourcePlatform).
Distinct().
Scan(&RuleList)
I don't quite understand why? The documentation doesn't clearly explain this distinction, and it would be helpful to have clarification on how Distinct
is intended to work in these scenarios.
Thank you!
The document you expected this should be explained
Expected answer
Comment From: github-actions[bot]
This issue has been automatically marked as stale because it has been open 360 days with no activity. Remove stale label or comment or this will be closed in 180 days