dongying6896 2013-07-26 12:18
浏览 110
已采纳

将表限制为100行,之后删除最后一行并将新的一行添加到顶部(MYSQL,PHP)

I have a table in database which records ip addresses

i need to have a maximum o 100 records for each user then delete the last record if the user reaches 100 records and add the new record to the top (newest)

what is the best method to do this with PHP or MYSQL QUERY, should i use num_rows with SELECT * ?

EDIT: I need to limit recording IPs for each user in database, not limit showing them (each user can't have more than 100 IPs in database)

EDIT 2: I was thinking of reading the date of 100th query and then delete each record with date < 100th query, is this a good practice?

  • 写回答

2条回答 默认 最新

  • dqa35710 2013-07-26 12:21
    关注
    $result = mysql_query("SELECT id FROM tablename WHERE user_id=123 ORDER BY id DESC LIMIT 100,1");
    $fetch = mysql_fetch_assoc($result);
    mysql_query("DELETE FROM tablename WHERE id <".$fetch['id']." AND user_id=123");
    

    You talk about selecting the date, always try to go for the fastest column. Your id column probally is auto_increment and has an index on it, which makes this a fast column. The date value is probally not indexed, thus slower
    Small sidenote: I'm using mysql_ functions, you should use mysqli_ functions


    I've tried these, but they dont not work (for me):

    DELETE FROM tablename WHERE user_id=123 LIMIT 100,9999
    

    Another way I wanted to try was this:

    DELETE FROM tablename WHERE user_id=123 
    WHERE id NOT IN(SELECT id FROM tablename WHERE user_id=123 ORDER BY id DESC LIMIT 100)
    

    But subqueries dont support a limit (maybe the more recent versions do, but mine doesnt)
    Marin Sagovac suggested this, but also did not work for me:

    DELETE FROM tablename WHERE user_id=123 LIMIT 10 OFFSET 100
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私