MySQL select rows from exactly 7 days ago

穿精又带淫゛_ 提交于 2019-11-29 03:06:40
Ghazanfar Mir

It is very rare to get same datetime entries which gives date and time upto seconds. Therefore, for getting appropriate results we need to ignore the time part, and deal with date part, thus, using CURDATE() function.

You could do that ignoring the time part and compare with the date using following:

function get_ad_sql($table){
    $sql = "SELECT 
                * 
            FROM 
                ".$table." 
            WHERE 
                DATE(edit_date) = DATE_SUB(CURDATE(), INTERVAL 7 DAY)
            ";  
    return $sql;
}

NOW() returns DATETIME value, you should use a DATE function to get date without time, e.g. -

SELECT * FROM table WHERE edit_date = DATE_SUB(DATE(NOW()), INTERVAL 7 DAY);

If type of edit_date field is DATETIME, then this field should be wrapped by DATE() function too -

SELECT * FROM table WHERE DATE(edit_date) = DATE_SUB(DATE(NOW()), INTERVAL 7 DAY);

Your script is working... I highly doubt you have something exactly 7 days ago (to the second).

Perhaps you wanted something WHERE edit_date>DATE_SUB(NOW, INTERVAL 7 DAY) AND edit_date<DATE_SUB(NOW, INTERVAL 6 DAY)?

Or, if you want to compare just the date (not the time) portions, compare the output of DATE() instead.

abi740
 SELECT SUBDATE(CURDATE(), 7)

Try this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!