gpt4 book ai didi

MYSQL:限制每个 whereIn() 的行数

转载 作者:太空宇宙 更新时间:2023-11-03 11:40:33 32 4
gpt4 key购买 nike

用户表

编号


user_comments 表

编号 |用户 ID |内容 |创建于


我有一个用户 ID 列表,我想为每个用户 ID 抓取最新的 3 条评论。

SELECT * FROM user_comments WHERE user_id IN (1, 2, 3, 4, 5) 
ORDER BY created_at DESC
LIMIT 3;

这将从所有匹配的ID中获取最后3条评论,我想要每个 ID的最后3条评论。首选 1 个不带联合的查询。

我试过自己正确加入表格,但我似乎无法正确加入。

** 编辑:我不能依赖 id 列进行排序,它必须使用日期列。

谢谢。


** 我的最终解决方案

SELECT user_comments.* FROM user_comments
LEFT OUTER JOIN user_comments user_comments_2
ON user_comments.post_id = user_comments_2.post_id
AND user_comments.id < user_comments_2.id
where user_comments.post_id in (x,x,x)
GROUP BY user_comments.id
HAVING COUNT(*) < 3
ORDER BY user_id, created_at

@PaulSpiegel 提出的答案确实对我有用(有警告),但是我最终采用了我使用此线程中的信息制作的上述连接解决方​​案:link

Bill Karwin 提到。

谢谢大家!

最佳答案

如果你可以使用id而不是created_at,你可以将id与第三高的id进行比较每个用户。您可以在带有 LIMIT 1 OFFSET 2 的子查询中找到它。对于用户少于 3 条评论的情况,使用 COALESCE(或 IFNULL)选择所有 id >= 0 的评论。

SELECT * 
FROM user_comments c
WHERE user_id IN (1, 2, 3, 4, 5)
AND id >= COALESCE((
SELECT id
FROM user_comments c1
WHERE c1.user_id = c.user_id
ORDER BY id DESC
LIMIT 1
OFFSET 2
), 0)
ORDER BY user_id, id DESC

如果您不能使用 id 进行订购..

SELECT * 
FROM user_comments c
WHERE user_id IN (1, 2, 3, 4, 5)
AND created_at >= COALESCE((
SELECT created_at
FROM user_comments c1
WHERE c1.user_id = c.user_id
ORDER BY created_at DESC
LIMIT 1
OFFSET 2
), '1970-01-01 00:00:00')
ORDER BY user_id, created_at DESC

请注意,如果第 3 条和第 4 条评论具有相同的时间戳,那么您可能会(尽管不太可能)收到超过 3 条评论。

关于MYSQL:限制每个 whereIn() 的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42124031/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com