Select timestamp interval of 2 weeks / days - mysql

Table: donate
Columns: donate_id, donate_active, donate_time
donate_time value is a unix_timestamp
I have to select all entries 2 weeks before reaching the donate_time, to send a reminder email.
I tried many ways, but I always get a syntax error.
SELECT * FROM donate
WHERE donate_time >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 2 WEEK))

According to this page, INTERVAL only supports WEEK from version 5, and you said you are running 4.1. Try 14 DAY instead of 2 WEEK.

I pasted your code and it works for me in MySQL Workbench 5.2.47.
Make sure you have a space after the table name and a semicolon at the end.
Check any surrounding code for sytax errors.
Here is the code I ran successfully. Try pasting back to your environment (change names).
SELECT * FROM requests
WHERE returntime >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 2 WEEK))

Related

how to display data from now until one week ago in mysql

I want to display the data from now until one week ago.
i have query uses the where statement as
WHERE date
BETWEEN
(CURRENT_DATE() - INTERVAL 1 WEEK)
AND
CURRENT_DATE();
It shows data for past 1 week but does not include today. What am i doing wrong here?
current_date will wait till midnight i.e. till the day/date is over. Use now() to display data till the current timestamp.
Make sure the datatypes (date/datetime/timestamp) are consistent. Cast them where ever required.
Important: Avoid using operators with the datatype they are not meant for. I see, you're using - (minus) with date/timestamp. A better way would be : subdate(now(), interval 1 week)

datediff() not ignoring time

I'm using MYSQL 5.5.47 on Debian and I have this bit in my query:
AND DATEDIFF(CURRENT_DATE(), shouts_stores.date) <= 7
-- changed it from AND DATEDIFF(NOW(), shouts_stores.date) <= 7
The problem?
Datediff, according to everything I've read, is supposed to ignore the time part.
I have to get rows of the last 7 days, but I need the timestamps with a time element for "Posted X seconds/minutes/hours/days ago" functionality in PHP.
However, when it comes to just getting the rows, I simply need the posts from up to (and including) 7 days (or 1 week) ago. However, if the posting time is earlier than it is right now, it'll knock it up to 8 days. This causes some confusion. Does anyone have any idea about this?
edit: example
This is what the table looks like:
tl dr; I need DATEDIFF() to ignore the time part of the datetime.
Try:
... DATEDIFF(CURRENT_DATE(), DATE(shouts_stores.date)) <= 7
Try this:
DATE_ADD(shouts_stores.date,INTERVAL 7 DAY) >= CURRENT_DATE()
replace CURRENT_DATE() with NOW() as needed

Mysql between reverse range

Hi I am comparing two dates using mysql between function. My query looks like
select count(id) as total
from table
where user_id=111
and date_column BETWEEN DATE_SUB(NOW(), INTERVAL 1 DAY)
and NOW()
In between part of this query it is BETWEEN upperdate and lowerdate. It is working fine. But I went to verify this function on mysql documentation https://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_between . It says it should be
`BETWEEN LOWER AND UPPER`
Current I am doing in reverse and it is working fine but I just want to verify that is it rite and it will cause in problem in future and any hidden case.
It is working. Because:
DATE_SUB(NOW(), INTERVAL 1 DAY) -- a day less than now is yesterday
is LOWER THAN
NOW() -- it is now, means today with current time
So comparison would be like
between yes'day and today
which is valid
BETWEEN DATE_SUB(NOW(), INTERVAL 1 DAY) and NOW()
is in other words
BETWEEN yesterday AND today
So it is
BETWEEN lower AND upper
No wonder it's working :)

Logic for dates in sql query for mysql

Hi i am totally confused with a date logic in my mysql query for a cron job to be run everyday at 12:00 AM
I am working on a auto listing website where the car listings are having a expiry date in mysql datetime format.
All the expired listings will be deleted from the website after 7 days from the datetime of the expiry
When the cron job will run it has do following things
Task 1 - Send an email alert to the users telling them that their listing has expired.
So I need to select all those listings which have expired since last time the cron job has been run and not include listings before that in order to send the expiry alert email only once per listing.
I tried following sql query for this task (Again confused with this as well)
SELECT car_id FROM cars WHERE expiry_date > DATE_SUB(NOW(), INTERVAL 1 DAY) AND expiry_date < NOW()
Task 2 - Will send an email alert to users telling them that listing is going to be permanently deleted after 24 hours.
So I need to select all those listings which are going to be deleted in more than 24 hours / 6 days have passed since they were expired and i need to make sure that they get minimum 24 hours time to renew them. Also i need to select / build the sql query in such a way that only those listings get selected which are going to expiry in 1 days and not other in order to avoid multiple email alerts instead of one time email alert
I tried following sql query for this task (I am totally confused with this query)
SELECT car_id FROM cars WHERE expiry_date > DATE_SUB(NOW(), INTERVAL 7 DAY) AND expiry_date < DATE_SUB(NOW(), INTERVAL 1 DAY)
Task 3 - Delete all the listings which were expired more than 7 days ago
I tried following sql query for this task
SELECT car_id FROM cars WHERE expiry_date < DATE_SUB(NOW(), INTERVAL 7 DAY)
Please help me in perfecting all the 3 queries so that the cron does it job exactly as i want. Also please let me where it has to >= (greater than or equal to) or <= (less than or equal to)
Here is the sqlfiddle table structure and couple of records (though they are not expired yet)
http://sqlfiddle.com/#!2/cfcdf
I will really appreciate the help.
Is this what you are looking for? Please try to add another column to see the differnce between expiry_date and current date time for you to get a better idea of the dates you are dealing with. Please look into some dates functions in MYSQL.
SQLFIDDLE DEMO
-- 3rd query expiry dates older than 7 days from
-- today
SELECT car_id, expiry_Date,
DATE_sub(NOW(), INTERVAL 7 DAY)
FROM cars
WHERE expiry_date <=
DATE_sub(NOW(), INTERVAL 7 DAY)
;
-- same
SELECT car_id, expiry_Date,
DATE_ADD(NOW(), INTERVAL -7 DAY)
FROM cars
WHERE expiry_date <=
DATE_ADD(NOW(), INTERVAL -7 DAY)
;
-- 2nd query going to expire in exactly 1 day
SELECT car_id, expiry_date,
Now() + interval 1 day
FROM cars
WHERE expiry_Date = Now() + interval 1 day
;
-- 1st query: expired
SELECT car_id FROM cars
WHERE expiry_date < Now()
;
-- 1st query: expired last 24 hours
SELECT car_id,DATEDIFF(expiry_date, Now())
FROM cars
WHERE expiry_Date < Now()
AND expiry_Date >= Now() - interval 1 day
;
Check out these queries
select * from cars where datediff(EXPIRY_DATE,now())=-1;
select * from cars where
datediff(DATE_ADD(EXPIRY_DATE, interval 24 hour),now())>=1 and
datediff(DATE_ADD(EXPIRY_DATE, interval 24 hour),now()) <=2;
select * from cars where datediff(expiry_date,now())<=-7;
ope they are working according to your need.
fiddle http://sqlfiddle.com/#!2/785ea/5
There is nothing significantly wrong with your queries, if you do not understand the functions that you have used then google them and read about them until you do.
There is a fundamental problem in your approach in that it relies on the cron job being run at exactly 24 hour intevals - to the milisecond - or there will be double ups and/or omissions.
You need another table to store details of when your batch program last ran; intitialise this with 1 row with a date a long time in the past so that we have a starting point.
You can get the most recent batch by SELECT MAX(date_ran) FROM BatchRecordTables. Store this in a local variable T0. Get the current time, store this in a local variable T1 (Do not use NOW() in multiple queries as they will be slightly differant times and you need them to be the same). I do not know the syntax for this is MySQL - you will have to look it up.
Your situations then become.
Send email to people whose listings have expired since that last time the cron job was run i.e. SELECT car_id FROM cars WHERE Expiry_Date BETWEEN T0 AND T1. This will only select people whoose listings have expired between this batch and the previous one.
For the second case, we need to know that these people have got the first email i.e. that their listing had expired before the last batch run so SELECT car_id FROM cars WHERE Expiry_Date BETWEEN DATE_SUB(T1, INTERVAL 6 DAY) AND T0. This will only select people whoose listings expired before the last batch (i.e. they got the exprired email) and more than 6 days ago.
Same logi applies - we want to know they got the second email. SELECT car_id FROM cars WHERE Expiry_Date BETWEEN DATE_SUB(T1, INTERVAL 7 DAY) AND DATE_SUB(T0, INTERVAL 6 DAY)
May I also suggest that you do not permenantly delete the listings but either copy them to a DeletedListings table or Flag them with a Deleted column - each has its own pros and cons. In the information age, never throw data away - you never know when it might be valuable.

How do I select two weeks ago in MYSQL?

I have a report that is driven by a sql query that looks like this:
SELECT batch_log.userid,
batches.operation_id,
SUM(TIME_TO_SEC(ramses.batch_log.time_elapsed)),
SUM(ramses.tasks.estimated_nonrecurring + ramses.tasks.estimated_recurring),
DATE(start_time)
FROM batch_log
JOIN batches ON batch_log.batch_id=batches.id
JOIN ramses.tasks ON ramses.batch_log.batch_id=ramses.tasks.batch_id
JOIN protocase.tblusers on ramses.batch_log.userid = protocase.tblusers.userid
WHERE DATE(ramses.batch_log.start_time) > "2011-02-01"
AND ramses.batch_log.time_elapsed > "00:03:00"
AND DATE(ramses.batch_log.start_time) < now()
AND protocase.tblusers.active = 1
AND protocase.tblusers.userid NOT in ("ksnow","smanning", "dstapleton")
GROUP BY userid, batches.operation_id, date(start_time)
ORDER BY start_time, userid ASC
Since this is to be compared with the time from the current payperiod it causes an error.
Our pay periods start on a Sunday, the first pay period was 2011-02-01 and our last pay period started the 4th of this month. How do I put that into my where statement to strip the most recent pay period out of the query?
EDIT: So now I'm using date_sub(now(), INTERVAL 2 WEEK) but I really need a particular day of the week(SUNDAY) since it is wednesday it's chopping it off at wednesday.
You want to use DATE_SUB, and as an example.
Specifically:
select DATE_SUB(curdate(), INTERVAL 2 WEEK)
gets you two weeks ago. Insert the DATE_SUB ... part into your sql and you're good to go.
Edit per your comment:
Check out DAYOFWEEK:
and you can do something along the lines of:
DATE_SUB(DATE_SUB(curdate(), INTERVAL 2 WEEK), INTERVAL 2 + DAYOFWEEK(curdate()) DAY)
(I don't have a MySql instance to test it on .. but essentially subtract the number of days after Monday.)
Question isn't quite clear, especially after the edit - it isn't clear now is the "pay period" two weeks long or do you want just last two weeks back from last sunday? I assume that the period is two weeks... then you first need to know how many days the latest period (which you want to ignore, as it isn't over yet) has been going on. To get that number of days you can use expression like
DATEDIFF(today, FirstPeriod) % 14
where FirstPeriod is 2011-02-01. And now you strip that number of days from the current date in the query using date_sub(). The exact expression depends on how the period is defined but you should get the idea...