gf icon indicating copy to clipboard operation
gf copied to clipboard

os/gtime: issue count与group同时存在且有多个字段查询问题

Open tkzl opened this issue 5 months ago • 1 comments

Go version

go 1.22

GoFrame version

2.8.2

Can this bug be reproduced with the latest release?

Option Yes

What did you do?

因业务需要查询多个字段的同时存在count与group时原查询会报错,需要改为以下方式,判断下是否存在group, 看了下新版本也是这样 database/gdb/gdb_model_select.go704行

case SelectTypeCount:
		queryFields := "COUNT(1)"
		if len(m.fields) > 0 {
			// DO NOT quote the m.fields here, in case of fields like:
			// DISTINCT t.user_id uid

			if len(m.groupBy) > 0 {
				queryFields = m.getFieldsAsStr()
			} else {
				queryFields = fmt.Sprintf(`COUNT(%s%s)`, m.distinct, m.getFieldsAsStr())
			}
		}
		// Raw SQL Model.
		if m.rawSql != "" {
			sqlWithHolder = fmt.Sprintf("SELECT %s FROM (%s) AS T", queryFields, m.rawSql)
			return sqlWithHolder, nil
		}
		conditionWhere, conditionExtra, conditionArgs := m.formatCondition(ctx, false, true)
		sqlWithHolder = fmt.Sprintf("SELECT %s FROM %s%s", queryFields, m.tables, conditionWhere+conditionExtra)
		if len(m.groupBy) > 0 {
			sqlWithHolder = fmt.Sprintf("SELECT COUNT(1) FROM (%s) count_alias", sqlWithHolder)
		}
		return sqlWithHolder, conditionArgs

What did you see happen?

SELECT COUNT(1) FROM (SELECT COUNT(cid,name,MAX(pay_time) AS pay_times) FROM abc WHERE ((aid=6) AND (bid=2)) AND delete_at IS NULL GROUP BY cid) count_alias
Error: Error 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ',`name`,MAX(`pay_time`) AS `pay_times`) FROM 

What did you expect to see?

SELECT COUNT(1) FROM (SELECT cid,name,MAX(pay_time) AS pay_times FROM abc WHERE ((aid=6) AND (bid=2)) AND delete_at IS NULL GROUP BY cid) count_alias

tkzl avatar Jul 15 '25 03:07 tkzl

贴一下你的代码

CyJaySong avatar Jul 26 '25 10:07 CyJaySong