Date 1 :- 2014-09-27 10:00:00
Date 2 :- 2014-09-29 11:00:00
This range is stored inside the database and it means that user has given time range for 2 days from 27 to 29 and timing from 27 -> 10:00:00 to 29 -> 11:00:00. This means that user will be available from 10 AM to 11 AM between 27 to 29, 2014.
Now if i pass 2014-09-28 13:00:00 which is in date range and also in time range because user specified the entire day for it as can be seen in the range.
SELECT * FROM TABLE_NAME WHERE Id = $Id AND DATE('$currentDate') BETWEEN DATE(From_DateTime) AND DATE(To_DateTime) AND TIME('$timeHour') BETWEEN TIME(From_DateTime) AND TIME(To_DateTime)
From_DateTime = Date1
To_DateTime = Date2
currentDate = 2014-09-28
timeHour = 13:00:00
Now the problem is that logically the parameter passed are within the range but using the query its not because in TIME its not checking the date, 13 is not between 10 & 11 so its not working. I have tried the DATETIME as well but its not working as giving me error.
I need a way to match date & time both at the same time. Anyone having any suggestion. I am using PHP as programming language.
If the values are stored in DATETIME like this format you mentioned
Date 1 :- 2014-09-27 10:00:00
Date 2 :- 2014-09-29 11:00:00
Then you don't even need all that complexity. Just use normal comparison operators
SELECT * FROM yourTABLE
WHERE startDate >= '2014-09-27 13:00:00'
AND endDate <= '2014-09-29 10:00:00'
Ofcourse you can use your PHP variables instead of the test dates I have there in the query. You can format your PHP values to be in line with MySQL date time format.
If you're expecting large result or large database, I would suggest you use the "BETWEEN".
But I would like to clarify your database schema has 2 fields to compare? Namely "To_DateTime" and "From_DateTime"? If so, I seconded Hanky's answer.
Related
I have a table called reports in MySQL(MariaDB) . There is a one(out of 5) column named logdate which is is of type datetime .columns stores the the date and time (in 24hr format) .
for ex here is sample value from that column
2021-04-10 09:35:00
I have to find all reports between a given date and time .
I get 4 variables from form data in PHP
$fromdate= $_POST['fromdate'];
$todate= $_POST['todate'];
$fromtime= $_POST['fromtime'];
$totime= $_POST['totime'];
$fromtime and $totime are just integers with value from 0-23 for hours.
For example the condition may be like get all data between 4th April 2021
from 5 o'clock To 8 April 2021 18 o'clock
i.e. From 2021-04-04 03:00:00 to 2021-04-08 18:00:00. There will be never condition on minutes and seconds .
My question is how to construct a datetime in PHP compatible with MySQL types so I can have good(efficient, there are millions of records in table ) search speed?
for ex
$select = "select * from reports where logdate between ? and ? ";
P.S: I tried saving date and time as integer as unixtime stamp. But when i convert from and to date received using strttotime() I facing time format issue due to bug in my code which so can use datetime only.
If you have any suggestion to improve efficiency of DB please suggest.Thanks
Hi this link may be of help in optimizing date comparison
MySQL SELECT WHERE datetime matches day (and not necessarily time)
This one below, will help you in formatting your strtotime() by using strptime()
https://www.php.net/manual/en/function.strptime.php
Also check your spelling or typo; you wrote "strttotime()" instead of "strtotime()" yours has an extra 't' in str"tto"time, it should be str"to"time, though without the double qoutes
Though I can't say for sure this is the most effective way but you can use hour(logdate) to compare with $fromdate and $todate
$select = "select * from reports where hour(logdate) between ? and ? ";
But it will only compare hour part. Please mention how you are getting date part to compare?
It is not a good idea to make a calculation on a field in the WHERE CLAUSE. In this case MySQL / MariaDB must calculate the value from this field to comapare it to see
if this ROW has this condition. So MySQL must read the whole table FULL TABLE SCAN and CANT use any INDEX.
A better way to do this is to store the calculation on fix site. Then MySQL calculated it only one time and can use a Index ( if there one) .
you can easy use a query like this:
$select = "SELECT * FROM reports where logdate between date(?) + INTERVAL ? HOUR AND date(?) + INTERVAL ? HOUR ";
to test see:
SELECT date('2021-04-05') + INTERVAL 16 HOUR;
result:
2021-04-05 16:00:00
Here is what is working for me after using Bernds solution .
I constructing datetime string in php
$fromstr ="$fromdate"." "."$fromtime".":00:00";
$tostr="$todate"." "."$totime".":00:00";
here is my query looks like for date of 7th April to 10th April
$ select = "SELECT * FROM reports where logdate >= '$fromstr' and logdate <= '$tostr' order by logdate";
after echoing it
"SELECT * FROM reports where logdate >= '2021-04-07 3:00:00' and logdate <= '2021-04-10 5:00:00' order by logdate";```
However I am not sure if can use index for logdate column and utilize it with above query.
My datetime format on my SQL Table looks like this
Table1:
Col1
FromDate
--------------------------
10 August 2017 - 02:10 pm
Col2
ToDate
--------------------------
10 August 2017 - 08:00 pm
What would be the applicable SQL SELECT query and or php code to check if ..
$submitFrdate = "10 August 2017 - 3:00PM";
$submitTodate = "10 August 2017 - 6:00PM";
will be compared to the table using it's DATE only if any of the dates from either the first or second variable collides to the dates of any of the 2 table columns? I understand that I can trim the time stamp using substr() to make it into just 10 August 2017 but the data on the table includes the time. Other than that, I am not sure whats the easiest way to make sure either of the submitted data doesn't hit either of the column's dates REGARDLESS of the time.
Thanks in advance.
MySQL has a function called STR_TO_DATE() which can reverse-format a date string into MySQL's native date format. Then you can do comparisons in the SQL.
Perhaps better solution is to use the DATETIME type for the column. Then you can directly do comparisons with them.
I am using two fields in one of my table named as "tbl_TimeTable" in MySQL. Field Names are Start Time and End Time. I need to store Open Time and Close Time using these 2 fields. Now the Problem is Open Time is 09:00:00 AM and End Time is 02:00:00 AM. I can not find my results using this query.
Select TIME_FORMAT(a.End_Time, '%r'), a.Company_ID
from tbl_timetable a WHERE
TIME_FORMAT('15:00:00', '%r') BETWEEN
TIME_FORMAT(Start_Time, '%r') AND TIME_FORMAT(End_Time, '%r')
Table contains:
2 as Company_ID and Start_Time = 09:00:00 and End_Time = 02:00:00
SELECT * FROM logs;
idDate accNum idMonths dDay dYear dType transacted_money dat
4 862065095 9 8 2015 Withdraw 2323 09/08/2015
5 862065095 9 8 2015 Deposit 333 09/08/2015
Please help me solve this problem I wanted to get the data so that I could manipulate them in PHP. But first I would like to test my query in mysql and that's what it came out. Theres no result. Why? is my query wrong ?
Well I guess my first picture was deleted the actual query that was done was
SELECT * FROM logs WHERE dat BETWEEN '9/8/2015' AND '9/13/2015';
Your dates are strings, not actual mysql dates, so they're being compared by STRING rules, which means:
'9/1/15' > '10/1/15' --> TRUE (september comes after october?)
because 9 is bigger than 1 in a string context.
Note that
'2015-09-01' > '2015-10-01' -> FALSE
Either fix your table to convert those varchar fields into proper date/datetime fields, or you'll have do silly hacks like
WHERE str_to_date(varcharfield, ...) BETWEEN '2015-09-01' AND '2015-10-'01'
note the format the dates in the above example. MySQL expects/requires dates to be in yyyy-mm-dd or yyyy-mm-dd hh:mm:ss format to parse them as dates. Anything else is simply a string.
mysql> select '9/1/15' > '10/1/15', '2015-09-01' > '2015-10-01';
+----------------------+-----------------------------+
| '9/1/15' > '10/1/15' | '2015-09-01' > '2015-10-01' |
+----------------------+-----------------------------+
| 1 | 0 |
+----------------------+-----------------------------+
1 row in set (0.00 sec)
Try using the following
WHERE DATE_FORMAT( `createdon` , '%Y-%m-%d' ) <= '2014-07-31'
AND DATE_FORMAT( `createdon` , '%Y-%m-%d' ) >= '2014-07-01'
31-07 is end date and 01-07 is start date
As several users pointed out this is a very bad way to do it since your dates are strings and don't follow the correct way mysql formats dates, but since you asked for it this is a way to do it:
SELECT * FROM test
WHERE
STR_TO_DATE(my_date, '%m/%d/%Y') BETWEEN '2015-09-09' AND '2015-09-12';
Demo.
P.S. To use BETWEEN you must provide a date like yyyy-mm-dd or yyyy-mm-dd hh:mm:ss.
DI've been searching stackoverflow for a while, but couldn't find a solution for my problem.
I need to check if the sum of all participants in a table of events with two date fields is higher than X. No problem so far, but here it comes. I need to get the maximum sum of participants in a 5 minutes interval.
My customer needs to know if at any point in time in a given date range there are more persons in his house than allowed.
Table of events:
id start_date end_date participants
1 2014-03-12 10:00:00 2014-03-12 20:00:00 10
2 2014-03-01 12:30:00 2014-03-14 21:53:00 43
3 2014-02-12 10:00:00 2014-03-13 20:00:00 21
4 2014-05-30 10:00:00 2014-05-30 20:00:00 54
...
What I've found so far are solutions for a single date field, but I have two:
Grouping into interval of 5 minutes within a time range
SELECT / GROUP BY - segments of time (10 seconds, 30 seconds, etc)
Right now I can only think of a php loop to query this, but I don't think this would very smart with possibly thousands of iterations in a date range. Also I can think of a MySQL FOR-Loop, but I don't know how to do this for a date range.
Does anybody know a solution for this problem? Is this even possible with MySQL?
Thanks in advance.
Edit:
A possible pseudo query would be something like that:
DATE_END = 2014-03-31 20:00:00
DATE_START = 2014-03-01 10:00:00
WHILE (DATE_START < DATE_END) {
SELECT SUM(participants)
FROM events WHERE start_date <= DATE_START + 5 minutes
AND end_date >= DATE_START
IF (participants > MAX_PARTICIPANTS) {
MAX_PARTICIPANTS = participants
}
DATE_START + 5 minutes;
}
A result should be like:
Maximum simultaneous participants: 74
This is a classic application for recursive queries, which MySQL doesn't support, unfortunately.
In lieu of that, what you need to do is develop a sequence of timestamps from the earliest to the latest time found in the table. Do this with a procedure or in code in another language that calls MySQL. Then it will be a simple matter to join your table to that and find the maximum.