简体   繁体   中英

Query X amount of days in the past

Running MySql and Yii I need to change a relational query that currently finds records for the current month to find all records for the last 45 days.

This is my current query:

    'itemCount' => array(self::STAT, 'Item', 'ItemId', 
              'condition'=>'SUBSTRING(DateMoved FROM 1 FOR 7) = 
              SUBSTRING(current_date - INTERVAL 0 month FROM 1 FOR 7)  
              AND Status="W"'),

I have tried modifying this and tried a different approach using strtotime but neither approach is working. Using self::STAT can I find all records for the last 45 days?

Use this query to get records of last 45 days

SELECT * FROM table_name t 
WHERE t.DateMoved >= DATE_ADD(CURDATE(), INTERVAL -45 DAY);

With your code

'itemCount' => array(self::STAT, 'Item', 'ItemId', 
'condition'=>'DateMoved >= DATE_ADD(CURDATE(), INTERVAL -45 DAY)
AND Status="W"'),
INTERVAL 45 DAY AND CURDATE()

如果您还有其他问题,请告诉我。

For getting records for last N day you may use simple SQL query condition like this:

DateMoved >= DATE_SUB(NOW(), INTERVAL 45 DAY)

Other words - compare record date with current date substract 45 days

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