douyi4297 2014-04-10 13:24
浏览 36
已采纳

如何从数据库中删除过期数据(取决于句点列)

I want to delete the data that expired.

I have two columns:
created_time : That contain a value indicate to time() function (ex: 1395836716).
period :That contain the period of the remain the row in database (ex: 3 or 7 or 15 or 30 per day).

I want to create a query to check on all rows in the table to know the rows that expired.
The problem is I don't know how to do that, but I tried.

$twentyFour = 60 * 60 * 24;
mysql_query("DELETE FROM content WHERE created_time + (period * $twentyFour ) > '" . time() . "' ");

But unfortunately, did not work as I expected.


Edit:

This is a result of row

enter image description here


Edit 2

I did it, by using php conditions:

$twentyFour = 60 * 60 * 24;
$query = mysql_query("SELECT * FROM content");
while ($data = mysql_fetch_assoc($query)) {
    if ($data['created_time'] + ($data['period'] * $twentyFour) < time()) {
        mysql_query("DELETE FROM content WHERE id = $data[id]");
    }
}

The previous code works fine as was I want.
the problem is the previous code will occurs more server load.
I want a query to doing as the previous code does without using conditions.

  • 写回答

3条回答 默认 最新

  • duanleiming2014 2014-04-11 10:32
    关注

    May I suggest you edit your data structure and include a new column delete_time?

    This delete_time should contain the UNIX timestamp of when your column should be deleted calculated from your given period.


    Assuming your POST data of the period is numerical value indicating the number of days to save the data for, delete_time should be calculated by

    $delete_time = time() + $_POST['period']*24*60*60;
    

    This way, your pruning/deleting query can just be a one-liner:

    mysql_query("DELETE FROM content WHERE delete_time < ".time());
    

    That query deletes all rows whose delete_time has passed the current time().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据