dqenv99518 2013-07-23 05:53
浏览 24
已采纳

调用数据库的子集,如何在db结束时循环记录1

Sorry, the title was hard to phrase.

Using PDO, I have a database with 100 records. A random number of records are chosen at a time and the ID of the last used is saved. Each time it grabs that random number of records it picks up where it left off last time starting with the saved ID. Easy so far.

My problem is if the last ID use was 94 (of 100) and the number of records is 10. I get the next 6 OK. But then need to restart at ID 1 and keep looping.

I could do it at the end of my loop by determining I am at last record ID and doing a new query starting at ID 1. But it seems a bit clunky, any thoughts on a better method?

To head off a duplicate post close, How to get a random range of 10 records from a database without overlapping the end boundary? is about getting a random subset that happens to start near the end.

  • 写回答

1条回答 默认 最新

  • dpoh61610 2013-07-23 06:09
    关注

    Assuming $lastID is the last used id and $myLimit is the number of records that you want to get.

    $qry = "SELECT id, field_01, field_02
        FROM (
            SELECT id, field_01, field_02
            FROM my_table
            WHERE id >= {$lastID}
            LIMIT {$myLimit}
            UNION 
            SELECT id, field_01, field_02
            FROM my_table
            WHERE id < {$lastID}
            LIMIT {$myLimit}
        ) tab
        LIMIT {$myLimit}";
    

    The ideas of this query are to do the following :

    1. Get data with id more or equal to $lastID, limited to $myLimit rows.
    2. Get data with id less than $lastID, limited to $myLimit rows.
    3. Union both queries above.
    4. Get the first $myLimit rows.

    Hopefully this help.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表