I've got a MySQL table of stays, where each stay is defined with a from_date and to_date column. And I want to find all stays in range defined by user. For example, given that there is a stay from 01.01.2015 to 01.03.2015 I want this entry to be included in reports from 01.01.2015 to 31.01.2015 but also from 01.02.2015 to 28.02.2015 and in 01.03.2015 to 31.03.2015.
I've got everything stored as timestamps (in seconds).
Could somebody, please, give an example how to achieve this?
Abstract MySQL query:
select *
from table_of_stays
where ( date($stay_from_date)
between date($report-start-date) and date($report-end-date))
and (date($stay_to_date) < date($report-end-date))
First part of the match: stay_from_date must be in the range of the report.
Second part of the match: stay_to_date must be before the end date of the report.
All $variables are mysql DATETIME types = 2011-09-21 08:21:22, see
MySQL reference: http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_date
You can use BETWEEN to select a date between two values, and combine it with an OR so you select either the from date or the to date:
SELECT * FROM your_table
WHERE (from_date BETWEEN 'date_1' AND 'date_2')
OR (to_date BETWEEN 'date_1' AND 'date_2');
See this related answer for more information, and keep in mind you will need to convert the user input dates to timestamps, or convert your timestamps to dates for the comparison.
Ok, thanks to the other answers I got the best results with
(stay_range_start<=selected_range_end) && (stay_range_end>=selected_range_start) in mysql:
SELECT * FROM stays
WHERE `t0`.`from_date` <= $to_date
AND `t0`.`to_date` >= $from_date
Related
I have a problem related to MySQL query, I use WAMPServer.
I have data in database which have range of dates but when I select data for example
select * from CHD WHERE addtime>='2018-06-15' and addtime<='2018-06-21';
It displays data from '2018-06-15' to '2018-06-20', data of 2018-06-21 are not displayed even if I do
select * from CHD where addtime='2018-06-21';
is not working
Please anyone can help me
This assumes that your column is of type datetime.
The shorthand version of your date in the filter clause is assumed to be at midnight of the date. Your values that you are attempting to retrieve have times after midnight of that date. You either need to define a timestamp along with the date, or you need to filter by the day after for less than equal to or the day before for greater than equal
I am using HTML input type="date" to allow users to input appointment dates.
Now I want to query the database and show all appointments that are "today" and in the future.
Not dates that have already passed.
Here is my SQL Script
$today = date('d-m-Y');
$sql = "SELECT *
FROM `client1`
WHERE `client` = '$customer'
AND DATEDIFF('$today', `date`) >= 0
ORDER BY `id` DESC";
Can someone guide me as to how I can achieve this?
I have seen several directions online but I want to have the sorting done at the moment of query.
I have solved the issue!
My date() format was incorrect because HTML input type="date" inserts YYYY-MM-DD into the database =/
$today = date('d-m-Y');
should be
$today = date('Y-m-d');
My operator >= should have been <= to show today and future dates.
Thanks everyone for the help. I should have tried fixing it for 5 more minutes before posting.
Why are you using PHP to compare dates in the database? I assume its a date field so you can use MySQL to do it for you:
SELECT *
FROM `client1`
WHERE `client` = '$customer'
AND DATEDIFF(date_format(now(), '%Y/%m/%d'), `date`) >= 0
ORDER BY `id` DESC
None of the responses have specified sargable predicates. If you perform an operation on a column in the where clause, there is no discernible stopping point.
where ... some_function( some_field ) = some_constant_value ...
Even if some_field is indexed, a complete table scan must be performed because there is no way to know if the output of the operation is also ordered.
From my understanding the date column is in a sortable form -- either a date field or a string in lexically sortable format 'yyyy-mm-dd'. That being the case, don't do any operation on it.
where ... some_field >= now() ...
Thus the system can use the result of now() as a target value to find exactly where in the index to start looking. It knows it can ignore all the rows with indexed values "down" from the target value. It has to look only at rows with indexed values at or "up" from the target value. That is, it performs an index seek to the correct starting point and proceeds from there. This could mean totally bypassing many, many rows.
Or, to put it bluntly, ditch the datediff and do a direct comparison.
I have problem with my MySQL query.
I would like to query for delete rows oldest by 7 day from my table. This table has day, month and year in different rows.
This is my query:
DELETE FROM
`logowanie_dj`
WHERE
`miesiac`
IN (
SELECT CONCAT(dzien,':', miesiac,':', rok) < 21:1:2014'
)
However mysql_query() is deleting all the rows.
I presume that you mean year, month and day are in different columns?
Then this might work:
DELETE FROM `logowanie_dj` WHERE CAST(CONCAT(dzien,':',miesiac,':',rok) AS DATE) < CAST('21:1:2014' AS DATE)
It creates a date value in the form dd:mm:yyyy from the cells of the row and deletes it if it is before 21:1:2014.
Please note that you obviously use some date format that is non-english. MySQL might have a problem with that, so that it could be you need to do this:
DELETE FROM `logowanie_dj` WHERE CAST(CONCAT(rok,'-',miesiac,'-',dzien) AS DATE) < CAST('2014-01-21' AS DATE)
check the date and time format is correct or not. Try with this format 'yyyy:mm:dd hh:mm:ss'
You may want to try casting the two strings into dates so it knows to do the comparison as dates.
"For best results when using BETWEEN with date or time values, use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE."
Source
* Backup your database before trying this *
DELETE FROM `logowanie_dj`
WHERE ABS(UNIX_TIMESTAMP()-UNIX_TIMESTAMP(CONCAT(rok,'-',miesiac,'-',dzien))) > 604800
Try with below code
DELETE FROM
`logowanie_dj`
WHERE
`miesiac`
IN (
SELECT CONCAT(dzien,':', miesiac,':', rok) < '2014:01:21 00:00:00'
)
I have a column in my database table that holds dates in the format (mmm-yy) Ex: Aug-13. I'm trying to select all dates after Jun-12. The problem is the column is a string so when I say WHERE column > 'Jun-12' it gives me values that are alphabetically greater than Jun-12 such as May-12, which is not what i want. Any thoughts on how to go about this?
Store dates as dates, not strings. That's the recommended way of doing it and I recommend changing your code accordingly.
In this case, you could use STR_TO_DATE function to compare the dates on the fly:
SELECT * FROM table_name WHERE column > STR_TO_DATE('Jun-12','%m-%y');
Hope this helps!
In this situation you'll should be able to convert to a date and then filter as required, the below code should give you a guide,
SELECT *
FROM Table
WHERE CAST('01-' + column AS DATETIME) > '01-JUN-12'
I am trying to get a report between two date and I don't know What is the best way, I did a query but sometimes it doesn't work and I dont know where the error is.
Thank you again.
I am saving datetime in mysql field type varchar with php date('h:iA d-m-Y').
Example in mysql row date:
09:22AM 26-06-2015
08:00AM 27-06-2015
10:00PM 28-06-2015
When I use this data example $since=01-06-2015 $until=30-06-2015 this works
But if I use this data $since=01-06-2015 $until=01-07-2015 this doesn't work.
$since = $_REQUEST['since'];
$until = $_REQUEST['until'];
mysql_query("select * from paradas where DATE_FORMAT(STR_TO_DATE(SUBSTR(date, 9),'%d-%m-%Y') , '%d-%m-%Y') between '".$since."' and '".$until."' ");
By storing your date and time as a VARCHAR, instead as a DATETIME you also change the comparison between two rows from a datetime comparison (chronological) to a string comparison (lexigrafical).
If you now (as in your example) chose a string representation, where the lexigrafical comparison provides different results than the chronological comparison, you can no longer use contructs like BETWEEN or operators like <= and friends.
Solution: If you want to store date and time information, use the DATETIME column type.
In addition to that let me direct you to this SO question for a discussion of your SQL query.
EDIT
Just to make that clear:
In a lexigraphical order '01-06-2015' < '20-06-2015' < '30-06-2015', which is the same as the chronological order
But in a lexigraphical order '01-06-2015' < '01-07-2015' < '20-06-2015', which is contrary to chronological order.