为什么我会为这些类似的查询获得不同的结果?
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 |
+--------+
答案 0 :(得分:1)
您正在比较字符串,而不是日期。尝试显式转换为所需的数据类型:
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;
答案 1 :(得分:1)
因为您正在比较字符串,而不是日期。
将字符串转换为日期的最简单方法是在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
您也可以缩短查询时间,因为MySQL本地返回布尔值为1/0。
SELECT DATE(CONCAT(2011, '-1-1'))
BETWEEN DATE('2011-1-1') AND DATE('2011-3-31') as status;
答案 2 :(得分:1)
因为它正在进行字符串比较。你应该使用mysl 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;