dongpu9481 2014-12-16 08:09
浏览 204

MySQL在SELECT - WHERE IN语句中获取每个id的最后5个条目

I would like to select last 5 entries for each of the id in a SELECT - WHERE IN statement.

//How to get last 5 entries for each id
SELECT * FROM table1
WHERE id IN (111,222,333,.....)
ORDER BY date DESC
LIMIT 5

EDIT: Example of how data structure

id  date    name
111 7-Nov   Anna
111 8-Nov   Belle
111 9-Nov   Mary
111 10-Nov  John
111 11-Nov  Robert
111 12-Nov  Gary
111 13-Nov  Rick
222 8-Apr   Sarah
222 9-Apr   Lee
222 10-Apr  Margaret
222 11-Apr  Lisa
222 12-Apr  Will
222 13-Apr  Alex
222 14-Apr  Kelly
222 15-Apr  Lucas

Desired results

id  date    name
111 13-Nov  Rick
111 12-Nov  Gary
111 11-Nov  Robert
111 10-Nov  John
111 9-Nov   Mary
222 15-Apr  Lucas
222 14-Apr  Kelly
222 13-Apr  Alex
222 12-Apr  Will
222 11-Apr  Lisa

I am not sure this can be done in mysql. I have tried looking at some answers posted and I can't find the answers.

  • 写回答

2条回答 默认 最新

  • dpa55065 2014-12-16 08:33
    关注

    It just pseudo code, but I think it works. try this

    SELECT

    id,

    SUBSTRING_INDEX(GROUP_CONCAT( some_column_1 ORDER BY date DESC),',',5)

    SUBSTRING_INDEX(GROUP_CONCAT( some_column_2 ORDER BY date DESC),',',5)

    ....

    FROM table WHERE id IN (111,222,333,.....) GROUP BY id;

    it look not like you want. I just showing how use GROUP_CONCAT and SUBSTRING_INDEX function, you apply this, you can find answer.

    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘