0

我想从 mysql 数据库中获取迄今为止的记录。我写了这个,但它不起作用:

$from_date = "2012-06-19";
$to_date = "2012-06-24";

SELECT * 
  FROM `contracts` 
 WHERE `indate` >= '$from_date' 
   AND `indate` <= '$to_date' 
 ORDER BY `id` DESC

我的日期是 : 2012-06-20, 2012-06-21, 2012-06-22,2012-06-23

4

2 回答 2

0

试试下面:

    SELECT * 
      FROM contracts 
     WHERE indate >= to_date('2012-06-19','yyyy-mm-dd') 
       AND indate <= to_date('2012-06-24','yyyy-mm-dd') 
     ORDER BY id DESC
于 2012-10-07T06:29:55.310 回答
0

你在做什么应该工作正常。我在工作中一直从这样的日期字段中进行选择。

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)

日期比较的神奇之处在于该字段是日期类型的。

于 2012-10-07T04:08:33.643 回答