I have two query conditions here, and I would think that these queries would result in the same data, but they don't.
// 1st Condition:
WHERE month(jurnal.time) >= '01'
AND month(jurnal.time) <= '06'
AND year(jurnal.time) = '2012'
// 2nd Condition:
WHERE jurnal.time > '2012-01-01'
AND jurnal.time <= '2012-06-30'
I want the first condition to result in the same data as the second conditions.
Thanks in advance.
Your first version includes jurnal.time = '2012-01-01', whereas your second condition does not (owing to the use of > rather than >=).
It isn't clear from your question what is the data type of the jurnal.time column:
if it's DATETIME or TIMESTAMP, your second example will not have included any time after 00:00:00 on June 30 so one must instead either take only the date part:
WHERE DATE(jurnal.time) BETWEEN '2012-01-01' AND '2012-06-30'
or else ensure that the comparisons include all times of the day:
WHERE jurnal.time BETWEEN '2012-01-01 00:00:00' AND '2012-06-30 23:59:59'
if it's DATE, this point will not have affected your examples but one can nevertheless simplify your second example to:
WHERE jurnal.time BETWEEN '2012-01-01' AND '2012-06-30'
I recommend the BETWEEN comparison operator with CASTs:
WHERE jurnal.time BETWEEN CAST('2012-01-01' AS DATE) AND CAST ('2012-06-30' AS DATE)
Be sure to cast the stings to the same type as the column of jurnal.time.
Your conditonals in the first query are trying to compare as if they were numbers the values returned from the date parsing functions, but i think they are just strings. '01' and '06' are interperted by sql as plain strings, not the numbers 1 and 6.
The second is sql is smart enough to convert the full date string representation into a date to use in the comparison.
Related
i'm working on codeigniter and mysql db. I have run in to a issue where i need to show recent data as per date.
i have table name tbl_tournament where i'm going to fetch tournament data whose tournament_end_date >= $todays_date
My Query
$today = date("d/m/Y");
$this->db->select('*');
$this->db->from('tbl_tournament');
$this->db->where('is_deleted', FALSE);
$this->db->where('tournament_end_date_time >=', $today);
$this->db->order_by('tournament_start_date_time');
$query = $this->db->get();
return $query->result_array();
the output of this query is empty array
array();
When i manually change tournament_end_date_time = 01/04/2018 in database and query $this->db->where('tournament_end_date_time >=', '01/04/2017'); i get results. But when i change date in query as $this->db->where('tournament_end_date_time >=', '31/12/2017'); i get empty array.
In Mysql database i have used varchar as the data type tournament_end_date_time
Thank in Advance.
You store datetimes as strings (with VARCHAR type), hence they're compared as strings - character by character. For obvious reasons, '3' character is greater than '1'. That's why with filter set...
WHERE tournament_end_date_time >= '31/12/2017'
... you'll only get the results where corresponding values start from '31/12' - in other words, of December, 31 (of 2017 - or any year after it).
To solve the problem, you can use STR_TO_DATE() MySQL function to convert the existing column value to an actual date. Note that the param will be treated as a date literal as it follows 'YYYY-MM-DD' format:
WHERE STR_TO_DATE(tournament_end_date_time, '%d/%m/%Y') >= '2017-12-31'
... or, in PHP syntax, following CodeIgniter conventions:
$this->db->where(array(
"STR_TO_DATE(tournament_end_date_time, '%d/%m/%Y') >=" => date("Y-m-d")
));
A better choice is doing a single-time update operation on this column to convert all its values to DATE type at once.
I am amazed. I forgot to include strtotime but realized that it works in any case. Why does this work?
if($_POST['active_to'] == '' || $_POST['active_to'] >= '2038-01-19'){
$postproduct->active_to = '2025-07-31';
}else{
$postproduct->active_to = $_POST['active_to'];
}
Because YYYY-MM-DD format happens to sort in the same order when using string comparison.
If you were using, say, DD-MM-YYYY format, it wouldn't have worked. Similarly, if you were using YYYY-M-D format (where a leading zero isn't required), it also wouldn't work (because "2010-5-10" comes after "2010-12-10" in string ordering).
"2010-10-05" is greater than "2000-10-05" not because 2010 > 2000, but because "20" = "20" and "1" > "0". The first character that differs between the two strings happens to sort in the right order.
Because the string will be compared lexically character by character.
is 2 larger than 2?
if no, is 0 larger than 0?
if no, ...
You can directly compare the dates only for greater then less then or equal as it is a string.
As long as you have date in YYYY-MM-DD format only. Because YYYY-MM-DD will always change in increment format.
Please keep in mind about the format. Otherwise you have to use strtotime function.
You compare strings. In this operation, strings are converted to the numbers. If you have format Y-m-d, it works well because first is year which is the biggest value (Y*365 days) then month, and then days.
Result can be invalid in some cases because of not equal values of days in month, etc.
Ref: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.types
IT works because you are doing a string comparison which will work in an or condition, so long as that condition is true.
My Queries looks like this
WHERE `Project`.`user_id` = 9
AND `Project`.`project_status` = 1
AND `Project`.`project_type_id` = 4
AND `Project`.`approval_date` >= '01/08/2012'
AND `Project`.`approval_date` <= '01/12/2012'
I do have a record that matches this criteria, I actually created the query based on one of the records but it does not return. I really do not want to use the BETWEEN because the application can either use start date or end date
You should convert '01/08/2012' and '01/12/2012' to MySQL date/time values using STR_TO_DATE()
e.g.
STR_TO_DATE('01/08/2012', '%d/%m/%Y')
Well that's really only part of the query -- any, "between" works differently than you imply - here's an excerpt from the MySQL manual:
•expr BETWEEN min AND max If expr is greater than or equal to min and
expr is less than or equal to max, BETWEEN returns 1, otherwise it
returns 0. This is equivalent to the expression (min <= expr AND expr
<= max) if all the arguments are of the same type. Otherwise type
conversion takes place according to the rules described in Section
11.2, “Type Conversion in Expression Evaluation”, but applied to all the three arguments.
All that aside what is the datatype of the "approval_date" column?
This looks as if it should work on first glance, however the values you have supplied are not valid datetimes. Try this instead
WHERE `Project`.`user_id` = 9
AND `Project`.`project_status` = 1
AND `Project`.`project_type_id` = 4
AND `Project`.`approval_date` >= '2012-01-08 00:00:00'
AND `Project`.`approval_date` <= '2012-01-12 00:00:00'
you can still use BETWEEN
WHERE `Project`.`user_id` = 9
AND `Project`.`project_status` = 1
AND `Project`.`project_type_id` = 4
AND (`Project`.`approval_date` BETWEEN '2012-01-08 00:00:00' AND '2012-01-12 23:59:59')
My main problem was getting the string to format into datetime. kissmyface was correct on just structuring it correctly so mysql could understand. So I used php to convert it before sending it out.
"Project.approval_date >= '".date("Y-m-d H:i:s", strtotime($start))."'";
"Project.approval_date <= '".date("Y-m-d H:i:s",strtotime($end))."'";
this was pretty much my solution. unless anyone knows away to do the exact same thing on mysql side.
im storing the timestamp in mysql database in (INT) column, And i want to search the rows with between the dates. Anyone would please help what should be the Sql query to find the rows between two dates?
dates are entered like
FROM DATE = 15-10-2011
END DATE = 01-11-2011
It depends on what algorithm you use to convert the date strings to int values.
If the algoritm is mototonic, for example: If a day (say 15-10-2011) is converted to n (say 5037), then the next day (16-10-2011) is always converted to n+1 (so 5038 in this example.)
then you could just use:
WHERE IntField BETWEEN MySpecialConvertDateToIntFunction('15-10-2011')
AND MySpecialConvertDateToIntFunction('01-11-2011')
If your field stores different timsetamps as different integers (and the conversion is monotonic), you could change the above code slightly to:
WHERE IntField >= MySpecial...Function('15-10-2011')
AND IntField < MySpecial...Function('02-11-2011') --- notice the date+1
But it's usually better to use a field of the MySQL DATE type for storing dates. Unless you want to store dates before 1000 or after 9999 off course.
If you want to store timestamps, there's also a TIMESTAMP type. Read the
MySQL docs: DATETIME, DATE, and TIMESTAMP Types
You can use The BETWEEN operator, which selects a range of data between two values. The values can be numbers, text, or dates.
You can see there:
http://w3schools.com/sql/sql_between.asp
I would ask you to set data type as timestamp/datestamp & then
//php code
$date1=date ('Y-m-d' , strtotime ( "15-10-2011") );
$date2=date ('Y-m-d' , strtotime ( "01-11-2011") );
//sql code
SELECT * FROM tbl_mytbl WHERE DATE(attr_date) <'$date2' AND DATE(attr_date) >'$date1'
Can you use the mysql FROM_UNIXTIME function dev.mysql.com - function from_unixtime
SELECT *
FROM 'table'
WHERE FROM_UNIXTIME(intTimestamp)
BETWEEN
date ('Y-m-d' , strtotime ( '15-10-2011') )
AND ('Y-m-d' , strtotime ( '01-11-2011'));
I had made a mistake with the date input but have fixed.
I had to do some date comparision and return a dataset. PHP sent the current date time, with a time with non leading zeros (8:00:00) for 8 am instead of (08:00:00). The case where there were no leading zeros, was giving wrong results. Can someone explain why ?
To test, run this SELECT IF(DATE_ADD('2011-03-20', INTERVAL '08:05:00' HOUR_SECOND) >= '2011-03-20 8:00:00',"yes","No")
result: No
AND
SELECT IF(DATE_ADD('2011-03-20', INTERVAL '08:05:00' HOUR_SECOND) >= '2011-03-20 08:00:00',"yes","No")
result: Yes
shouldn't both give the result : "Yes"
Is it doing string comparison for a non leading zero ?
I think this is to do with MySQL's rather dodgy date / time handling in som ecases MySQL converts to a numeric and in other cases it uses string comparisons.
From the manual
http://dev.mysql.com/doc/refman/5.0/en/using-date.html
When you compare a DATE, TIME, DATETIME, or TIMESTAMP to a constant string with the <, <=, =, >=, >, or BETWEEN operators, MySQL normally converts the string to an internal long integer for faster comparison (and also for a bit more “relaxed” string checking). However, this conversion is subject to the following exceptions:
When you compare two columns
When you compare a DATE, TIME, DATETIME, or TIMESTAMP column to an expression
When you use any other comparison method than those just listed, such as IN or STRCMP().
For these exceptional cases, the comparison is done by converting the objects to strings and performing a string comparison.
Strictly speaking, you are comparing against strings (not dates) and relying on automatic casting. Try this instead:
SELECT
IF(DATE_ADD('2011-03-20', INTERVAL '08:05:00' HOUR_SECOND) >= STR_TO_DATE('2011-03-20 8:00:00', '%Y-%m-%d %H:%i:%s'), 'Yes', 'No'),
IF(DATE_ADD('2011-03-20', INTERVAL '08:05:00' HOUR_SECOND) >= STR_TO_DATE('2011-03-20 08:00:00', '%Y-%m-%d %H:%i:%s'), 'Yes', 'No')
Update:
According to the manual, DATE_ADD() can return a date or a string:
The return value depends on the
arguments:
DATETIME if the first argument is a DATETIME (or TIMESTAMP) value,
or if the first argument is a DATE and the unit value uses HOURS,
MINUTES, or SECONDS.
String otherwise.
To ensure that the result is DATETIME,
you can use CAST() to convert the
first argument to DATETIME.
So the left operand of the >= comparison is a string thus you're getting string comparisons. Try the CAST('2011-03-21' AS DATE) suggestion.