Skip to content

需要 Pluck 下支持 Having 查询 #7405

Open
@hupeh

Description

@hupeh

我有段代码如下:

sql := db.ToSQL(func(tx *gorm.DB) *gorm.DB {
    var total int64
    return tx.
        Table("fa_iot_card c").
        Joins("left join fa_card_flow_logs l on l.cardno = c.cardno").
        Select("count(c.id) as card_count", "count(l.id) as log_count").
        Where(clause.And(
                clause.Gte{Column: "l.start_time", Value: days[0]},
                clause.Lte{Column: "l.end_time", Value: days[len(days)-1]},
                clause.Gt{Column: "l.real_used_flow", Value: 0},
        )).
        // 注意:这里使用 Having 来限制查询结果
        Having("log_count > 0"). 
        // 然后这里使用 pluck 来查询数量
        Pluck("card_count", &total)
})

fmt.Println(sql)

我们考虑下,上面的 sql 语句是不是应该如下:

SELECT count(`c`.`id`) as `card_count`,  count(`l`.`id`) as `log_count` FROM fa_iot_card c left join fa_card_flow_logs l on l.cardno = c.cardno WHERE `l`.`start_time` >= '2025-03-31 00:00:00' AND `l`.`end_time` <= '2025-03-25 00:00:00' AND `l`.`real_used_flow` > 0  HAVING log_count > 0

但实际上,Pluck 会清理掉通过 Select 指定的查询字段,所以结果却是:

SELECT `card_count` FROM fa_iot_card c left join fa_card_flow_logs l on l.cardno = c.cardno WHERE `l`.`start_time` >= '2025-03-31 00:00:00' AND `l`.`end_time` <= '2025-03-25 00:00:00' AND `l`.`real_used_flow` > 0  HAVING log_count > 0

我引用的库:

module main

go 1.23.4

require (
    gorm.io/driver/mysql v1.5.7
    gorm.io/gorm v1.25.12
)

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions