How can I check if a date is in range in MySQL?
Why do I get different results for this similar queries?
SELECT CASE WHEN CONCAT(2011, '-1-1') BETWEEN '2011-01-01' AND '2011-03-31' THEN 1 ELSE 0 END AS status;
+--------+
| status |
+--------+
| 0 |
+------开发者_如何转开发--+
SELECT CASE WHEN CONCAT(2011, '-1-1') BETWEEN '2011-1-1' AND '2011-3-31' THEN 1 ELSE 0 END AS status;
+--------+
| status |
+--------+
| 1 |
+--------+
Because you are comparing strings, not dates.
The easiest way to turn a string into a date is to wrap in DATE().
SELECT CASE WHEN DATE(CONCAT(2011, '-1-1'))
BETWEEN DATE('2011-1-1') AND DATE('2011-3-31')
THEN 1 ELSE 0 END AS status;
http://dev.mysql.com/doc/refman/5.0/en/datetime.html
You can also make your query shorter, since MySQL returns boolean as 1/0 natively.
SELECT DATE(CONCAT(2011, '-1-1'))
BETWEEN DATE('2011-1-1') AND DATE('2011-3-31') as status;
You're comparing strings, not dates. Try explicitly casting to the desired datatype:
SELECT CASE WHEN CAST(CONCAT(2011, '-1-1') AS DATETIME) BETWEEN CAST('2011-01-01' AS DATETIME) AND CAST('2011-03-31' AS DATETIME) THEN 1 ELSE 0 END AS status;
Because it's doing a string comparison. You should use the mysl date function.
SELECT CASE WHEN date(CONCAT(2011, '-1-1')) BETWEEN date('2011-1-1') AND date('2011-3-31') THEN 1 ELSE 0 END AS status;
精彩评论