sql - Select with limit for the same id
问题描述
i have 3 tables
Posts_comments
comment_id, comment_post_id, comment_value, comment_time comment_user_id
1 1 test DATETIME 1
2 1 test2 DATETIME 2
3 2 test3 DATETIME 2
4 1 test4 DATETIME 2
5 1 test5 DATETIME 1
6 1 test6 DATETIME 2
Members
member_id member_fistname member_lastname member_slug
1 John Doe john-doe
2 Test User test-user
Members_photos
member_user_id member_photo_type member_photo_name
1 2 test.jpg
2 2 test2.jpg
And i have sql
SELECT
posts_comments.comment_id,
posts_comments.comment_post_id,
posts_comments.comment_value,
posts_comments.comment_time,
members.member_id,
members.member_lastname,
members.member_fistname,
members_photos.member_photo_name
FROM
posts_comments
LEFT JOIN
members ON posts_comments.comment_user_id = members.member_id
LEFT JOIN
members_photos ON members.member_id = members_photos.member_user_id
AND
members_photos.member_photo_type = 2
ORDER BY
posts_comments.comment_time DESC
LIMIT 4
But this query show only last 4 comments independently from the comment_post_id. In this case i want to show last 4 comments for every comment_post_id (in this example: 4 comments where comment_post_id = 1 and 1 comment where comment_post_id = 2). I hope I wrote it clearly enough. Thx 4 help :)
解决方案
row_number()
如果是 mariadb 版本MariaDB 10.2.0
或更高版本,则使用窗口函数
select a.* from ( SELECT
posts_comments.comment_id,
posts_comments.comment_post_id,
posts_comments.comment_value,
posts_comments.comment_time,
members.member_id,
members.member_lastname,
members.member_fistname,
members_photos.member_photo_name,
row_number()over(partition by posts_comments.comment_post_id order by posts_comments.comment_time desc) rn
FROM
posts_comments
LEFT JOIN
members ON posts_comments.comment_user_id = members.member_id
LEFT JOIN
members_photos ON members.member_id = members_photos.member_user_id
AND
members_photos.member_photo_type = 2
) a where a.rn<=4
推荐阅读
- css - 以闪亮的方式对齐可变数量的文本输入
- url - 在打开的 url 操作表达式中传递硬编码值 - SSRS
- reactjs - React Hooks 从对象状态中获取数据
- excel - Excel Office 365、Concat 和 2x VLookup 生成唯一字符串
- python - Python - 如何一次有效地在压缩存档中写入/读取 JSON 文件?
- python - 在 pandas 数据框中迭代地保存输出
- mysql - 是否可以使用颜色设置 MYSQL_PS1 而不会弄乱提示线宽计算?
- python - 无法解决python停止者密码中的此错误
- python - 将自动编码器预测图像保存到新目录时出现问题
- vue.js - Vue CLI 项目导入 CJS 模块失败