简体   繁体   中英

Get all rows before a specific day

We are using the below updated SQL to get customers list from our db whom we send SMS before 3 days.

SELECT * FROM sms WHERE sent_time >= NOW() - INTERVAL 3 DAY;

The table sms is updated daily along with the sent_time column with default value of 0 or the last sent time.

There are rows with the value of sent_time = 0 but no row is fetched by the above script.

What is the correct SQL?

Earlier we were using the SQL with php like mentioned below:

$vTime = time() - ( 60*60*24*3 );
$sql = "SELECT * FROM sms WHERE $vTime <= sent_time";

The function NOW() will return current date and time, but as I can see you have used PHP time() before, which returns a Unix-Timestamp. The SQL equivalent is UNIX_TIMESTAMP() .

Syntax UNIX_TIMESTAMP()

SELECT * FROM sms WHERE sent_time >= UNIX_TIMESTAMP() - (60*60*24*3);

Syntax UNIX_TIMESTAMP(date)

SELECT * FROM sms WHERE sent_time >= UNIX_TIMESTAMP(NOW() - INTERVAL 3 DAY) OR sent_time = 0

NOW() - INTERVAL 3 DAY; returns a DATETIME while echo time() - ( 60*60*24*3 ); returns a timestamp.

If your database column is a timestamp, your MySQL test will never work, use this instead:

SELECT * FROM sms WHERE sent_time >= UNIX_TIMESTAMP(NOW() - INTERVAL 3 DAY)

只需更改选择查询即可。

SELECT * FROM sms WHERE sent_time >= DATE_SUB(NOW(), INTERVAL 3 DAY) AND NOW();

请尝试以下方法:

SELECT * FROM sms WHERE sent_time <= DATE_SUB(NOW(), INTERVAL 3 DAY) OR sent_time=0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM