List items dependent on a time limit - mysql

Im trying to come up with an SQL query that will list the rows that are within a certain time span which depends on the current time. The function which will call this query will check if the user is in the system, otherwise it will list him as absent.
So a class starts at 9:00 for example, the query should compare the ScheduleTimeStart and ScheduleTimeEnd, with the current time. The query should list a row only if the time is 9:00 and onwards, but do not list a row if the current time exceeded the 30 minutes cooldown period. So in other words from 9:00 - 9:30.
What I have done so far:
SELECT studentID, scheduleID, scheduleDate, scheduleTimeStart, scheduleTimeEnd, schedule.classID, schedule.unitsID
FROM schedule
JOIN schedule_students USING(scheduleID)
JOIN students USING(studentID)
WHERE scheduleDate=CURDATE()
AND scheduleTimeStart >= CURTIME() //Gordons answer
AND scheduleTimeStart < CURTIME() + interval 30 minute// but its not working
AND studentID=1003;

First, learn to use parameters. Don't munge SQL strings with values. This can lead to syntactic errors and SQL injection vulnerabilities.
SELECT s.*
FROM schedule s
WHERE scheduleID = ? AND classID = ? AND unitsID = ? AND
DATE(scheduleDate) = CURDATE() AND
scheduleTimeStart >= CURTIME() AND
scheduleTimeStart < CURTIME() + interval 30 minute;
It is not clear if you want the same condition on the scheduleTimeEnd as well.

Related

UPDATE sql to change time only in datetime

I want to UPDATE time only from datetime using sql but it seem cant work. the update will get from user and only change the time.
example 2018-10-06 08:00:00 update to 2018-10-06 12:00:00 (time that user enter)
$sql3="UPDATE course
SET date_start = '$date_start'
WHERE date_start = SUBSTRING(date_start,11,17)
AND CourseNo = '$id1' ";
$hasil3=mysql_query($sql3);
if($hasil3==false)
echo "SQL error:".mysql_error();
else
{
?> <center>
<script language="javascript">
alert("Successfully update!");window.location="studentTimetable.php";
</script>
You can use an expression such as:
select date('2018-10-06 08:00:00') + interval 12 hour
You can also use addtime() if you want to add hours/minutes/seconds.
This should be simple enough to put into an update statement if that is what you want to do.
If I understand you right, you get an input as string in the format <hours> ":" <minutes> ":" <seconds>, that represents a time of the day. You want to replace the time of the day portion of a datetime column with that given time of the day.
To do so you can first downcast the column to a date and then upcast it again to a datetime. That way the time of the day portion becomes 00:00:00. Now use date_add to add the time of the day the user has given to you. Since the time of the day was zeroed before that will result in a datetime with the time of the day as the user put in.
UPDATE elbat
SET nmuloc = date_add(cast(cast(nmuloc AS date) AS datetime), INTERVAL '12:00:00' HOUR_SECOND);
I had a similar problem to this..
I have a number of dates that are not quite right by a few seconds. They should all end on an Hour, i.e 00:00
Work out how much time I need add (I know i want to add some seconds)
SELECT 60 - DATEPART(SECOND, EndDate), e.*
FROM Events e
WHERE DatePart(SECOND, EndDate) <> 0
Now I can write an update to correct all the dates that are slightly off.
UPDATE Events
SET EndDate = DATEADD(SECOND, i.Seconds, i.EndDate)
FROM (
SELECT Id, 60 - DATEPART(SECOND, EndDate) AS Seconds, EndDate
FROM Events e
WHERE DatePart(SECOND, EndDate) <> 0
) i
WHERE
i.ID = Events.ID

Find data of a whole month in sql

I have this query where I provide to-date & from date.
SELECT *
FROM sales
WHERE date between to-date AND from-date;
Now I want to execute this query with following parameters
to-date = Oct-2015
some-other-date = Oct-2015
That is I want records of the whole month.
How would I do that in a query where I have to and from dates provided it will work for both scenarios where months can be same and different as well.
Update:
dataType for column date is date
You can find the first day of the month containing any given timestamp with an expression like this. For example by using the timestamp NOW(), this finds the first day of the present month.
(DATE(NOW() - INTERVAL DAYOFMONTH(DATE(NOW()))
That's handy, because then you can use an expression like
(DATE(NOW() - INTERVAL DAYOFMONTH(DATE(NOW())) - INTERVAL 1 MONTH
to find the beginning of the previous month if you like. All sorts of date arithmetic become available.
Therefore, you can use an expression like the following to find all records with item_date in the month before the present month.
WHERE item_date>=(DATE(NOW()-INTERVAL DAYOFMONTH(DATE(NOW()))- INTERVAL 1 MONTH
AND item_date < (DATE(NOW()-INTERVAL DAYOFMONTH(DATE(NOW()))
Notice that we cast the end of a range of time as an inequality (<) to the moment just after then end of the range of time.
You may find this writeup useful. http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/
It's often useful to create a stored function called TRUNC_MONTH() to perform the conversion of the arbitrary timestamp to the first day of the month. It makes your SQL statements easier to read.
select * from sales
where from-date >= 1-Oct-2015
and to-date <= 1-Nov-2015
Update
select * from sales
where date >= from-date
and date <= to-date
Here is SQLFIDDLE
You Can get month from your both to and from dates and find records of that month
SELECT * FROM sales
WHERE MONTH('2002-01-03') AND MONTH('2002-01-3')
SqlFiddle of Using Month Function

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.

Retrieve data whose Date between start and end date is between today and after ten day in rails or sql

I want to retrieve data whose Date between start and end date is between today and after ten day.I'm doing it in rails but even if i get the query in MySQL i can convert it to rails active record.
Something like this one :
select * from users where( between users.from and users.to = between '2012-11-25 11:52:33' and '2012-12-05 11:52:33')
The interval (a, b) overlaps with (c, d) iff a < d and b > c. Also, the curdate() function returns the current date ("today"). To calculate the date ten days into the future you can use + interval 10 day.
Combining these bits of information you get:
select ... where users.to > curdate()
and users.from < curdate() + interval 10 day
Follwing is the logic snippet not the exact code though. Please try.
select * from users
where users.fromDate between '2012-11-25 11:52:33' and '2012-12-05 11:52:33'
and users.toDate between '2012-11-25 11:52:33' and '2012-12-05 11:52:33';
Check the following sample code in * SQLFIDDLE as well
EDITING AS PER YOUR QUESTION'S REPHRASING..
Guess you are better off with,
where users.from between users.from and users.from + interval 10day
and users.to <= user.from + interval 10 day
That means, your from date can be anything (today, yesterday, one month back, two years to future...). Hence your to-date will be validated against any date that is 10 days interval from the above from-date
Hope it makes sense... but again, Joni's answers fills for your today's consition. :)

SQL Dealing with midnight

I'm dealing with (for me) huge SQL problem. I have table called "timeshifts" which as 4 columns:
id, name, from and to. Last two type is TIME.
Now: I have three timeshifts:
06:00 - 14:00
14:00 - 22:00
22:00 - 06:00
Now, I have to find correct shift for current time (which works like a charm), but I can't find a proper records that belong to current shift. IE. table called user_times contains fields with separate date and time values. According to current timeshift I have to find records that belongs to the timeshift. There is no problem for first two shifts, but third one passes midnight and that is my problem.
Here is the query that finds proper shift, event through midnight:
SELECT
FLOOR(SUM(time_sum) / 60) AS th,
MOD(SUM(time_sum), 60) AS tm,
t.*
FROM
ur_user_times ut,
ur_timeshifts t
WHERE CURTIME() >= IF (
t.timeshift_to < t.timeshift_from,
0,
ADDTIME(t.timeshift_from, "00:15")
)
AND CURTIME() <= ADDTIME(
IF (
t.timeshift_to < t.timeshift_from,
ADDTIME(t.timeshift_from, "10:00:00"),
t.timeshift_to
),
"00:15"
)
AND ut.`date` BETWEEN CURDATE() - INTERVAL 1 DAY AND CURDATE()
AND ut.`start` BETWEEN ADDTIME(t.`timeshift_from`, "-10:00:00") AND ADDTIME(t.`timeshift_to`, "-10:00:00")
AND ut.user_id = 40
ut.start is time value that interests us.
Try this:
select *
from timeshifts ts,
usertimes ut
where
(ts.from < ts.to and ut.start >= ts.from and ut.start <= ts.to) OR
(ts.from > ts.to and (ut.start >= ts.from or ut.start <= ts.to))
A similar query was posted a few days ago:
Please see this question:
Shift wise datetime checking in sql server query