你在做什么应该工作正常。我在工作中一直从这样的日期字段中进行选择。
mysql> create table contracts (indate date);
Query OK, 0 rows affected (0.02 sec)
mysql> insert into contracts values ('2012-10-06'), ('2012-11-04'), ('2012-09-17');
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> set @from_date = '2012-10-01';
Query OK, 0 rows affected (0.00 sec)
mysql> set @to_date = '2012-10-31';
Query OK, 0 rows affected (0.00 sec)
mysql> select * from contracts where indate >= @from_date and indate <= @to_date;
+------------+
| indate |
+------------+
| 2012-10-06 |
+------------+
1 row in set (0.00 sec)
我当然在这里使用了 mysql 变量,但它们什么都没有;它们只包含字符串。你可以这样做:
mysql> select * from contracts where indate >= '2012-10-01' and indate <= '2012-10-31';
+------------+
| indate |
+------------+
| 2012-10-06 |
+------------+
1 row in set (0.00 sec)
OP 是对的,BETWEEN 更简洁:
mysql> select * from contracts where indate between '2012-10-01' and '2012-10-31';
+------------+
| indate |
+------------+
| 2012-10-06 |
+------------+
1 row in set (0.00 sec)
日期比较的神奇之处在于该字段是日期类型的。