2011-04-05 91 views
1

爲什麼我會爲這個類似的查詢得到不同的結果?如何檢查日期是否在MySQL的範圍內?

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 | 
+--------+ 

回答

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; 
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

'CAST(CONCAT(2011,'-1-1')AS DATE)'也應該這樣做。 – 2011-04-05 18:55:44

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; 
相關問題