gorm 子查询

//实现代码
//GetLatelyUserOperationFlow 获取每个列表数据中的最近一条的未读消息
func GetLatelyUserOperationFlow(orgId int32, objectId []int32) (userOperationFlowList []*TUserOperationFlow) {
    var subQuery = dao.InnerDao.Gorm.Table(TableUserOperationFlow(orgId)).Select("objectId objectId1 , max(createTime) createTime1 ").Where(" `status` = 2 and objectId in (?) ", objectId).Group("objectId").SubQuery()
    dao.InnerDao.Gorm.Table(TableUserOperationFlow(orgId)).Select(
        fmt.Sprintf("%s,%s,%s,%s,%s,%s,%s",
            TUserOperationFlowColumns.FlowID,
            TUserOperationFlowColumns.OperatorUserID,
            TUserOperationFlowColumns.EventType,
            TUserOperationFlowColumns.ObjectID,
            TUserOperationFlowColumns.ContentInfo,
            TUserOperationFlowColumns.CreateTime,
            TUserOperationFlowColumns.Status)).Joins(" join (?) as M on objectId = objectId1 and createTime = createTime1  ", subQuery).Scan(&userOperationFlowList)
    return userOperationFlowList
}

最终生成的sql

SELECT flowId,operatorUserId,eventType,objectId,contentInfo,createTime,status FROM  t_user_operation_flow_2817360   join ((SELECT objectId objectId1 , max(createTime) createTime1  FROM  t_user_operation_flow_2817360   WHERE ( `status` = 2 and objectId in (1,3) ) GROUP BY objectId)) as M on objectId = objectId1 and createTime = createTime1     
stay hungry stay foolish!
原文地址:https://www.cnblogs.com/chongyao/p/15263164.html