SQL查询无法正常工作

时间:2012-10-07 03:55:15

标签: php mysql sql

我想从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-202012-06-212012-06-222012-06-23

2 个答案:

答案 0 :(得分: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)

O.P.是正确的,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)

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

答案 1 :(得分: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
相关问题