0

如何选择 mysql 中以“2012-02”开头的所有字段?

我试过的:

mysql> SELECT title,id FROM dle_post WHERE approve='1' AND date = '2012-02-13 21:35:00';
+-------------------------------------------------+----+
| title                                           | id |
+-------------------------------------------------+----+
| test title                                      |  7 |
+-------------------------------------------------+----+


mysql> SELECT title,id FROM dle_post WHERE approve='1' AND date='2012-02%';
Empty set, 2 warnings (0.00 sec)

mysql> SHOW WARNINGS;
+---------+------+-----------------------------------------------------------------+
| Level   | Code | Message                                                         |
+---------+------+-----------------------------------------------------------------+
| Warning | 1292 | Incorrect datetime value: '2012-02%' for column 'date' at row 1 |
| Warning | 1292 | Incorrect datetime value: '2012-02%' for column 'date' at row 1 |
+---------+------+-----------------------------------------------------------------+
4

4 回答 4

2

理想情况下,日期应被视为日期,而不是字符串。此查询应返回 2012 年 2 月的所有行,并且应该优于LIKE %查询:

SELECT title, id
FROM dle_post
WHERE approve = 1 
AND date >= '2012-02-01' 
AND date <  '2012-02-01' + INTERVAL 1 MONTH
于 2012-12-12T17:06:49.910 回答
0

改成

SELECT title,id FROM dle_post WHERE approve='1' AND date LIKE '2012-02%';
于 2012-12-12T17:06:30.287 回答
0

使用 like 运算符检查这些值

SELECT title,id FROM dle_post WHERE approve='1' AND date LIKE '2012-02%';
于 2012-12-12T17:07:02.770 回答
0

你有没有尝试过

date LIKE '2012-02%'

代替

date='2012-02%'

您可能还必须使用 DATE_FORMAT(date,format) 将日期转换为字符串

见:http ://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

于 2012-12-12T17:10:49.890 回答