通过MySQL窗口函数获取最新未读消息数据

WITH RankedMessages AS (
    SELECT 
        m.id, m.title, m.type, m.event_type, m.pusher_uid, 
        m.message, m.created_at, m.notifier_uid,
        ROW_NUMBER() OVER (PARTITION BY notifier_uid, type ORDER BY id DESC) as rn
    FROM messages m
    WHERE m.is_read = 0 
    AND m.deleted_at IS NULL
    -- AND notifier_uid IN (1, 2, 3, 4)  -- 可选:限制特定用户
)
SELECT id, title, type, event_type, pusher_uid, message, created_at, notifier_uid
FROM RankedMessages
WHERE rn = 1

GORM中使用:

showFields := []string{"id", "title", "type", "event_type", "pusher_uid", "notifier_uid", "message", "created_at"}
		subQuery := mysql.GetDbConnection().Debug().Model(msg).
			Select(append(showFields, "ROW_NUMBER() OVER (PARTITION BY type ORDER BY id DESC) as rn")).
			Where("is_read = ? AND notifier_uid = ?", 0, userId)

		lastMessages := make([]*model.Message, 0, len(messageCountTotal))
		err = mysql.GetDbConnection().Debug().Table("(?) as ranked_messages", subQuery).
			Select(showFields).
			Where("rn = 1").
			Scan(&lastMessages).Error

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值