mysql date_format无效返回空

时间:2017-10-04 15:06:19

标签: mysql sql

我在从数据库获取结果时遇到问题,DATE_FORMAT函数返回null或返回格式化日期。

表列及其数据类型:

paid_amount - >浮

created_at - > VARCHAR(100)

bellow是查询:

SELECT SUM(paid_amount) AS amount, 
date_format(created_at,'%Y-%m-%d') as dated 
FROM `job_card` 
WHERE date_format(created_at,'%Y-%m-%d') >= '2017-09-03' AND 
date_format(created_at,'%Y-%m-%d') <= '2017-10-03' GROUP BY date(created_at)

我正在使用另一种使用UNIX_TIMESTAMP函数转换日期到时间戳的方法,但仍然遇到同样的问题:

SELECT SUM(paid_amount) AS paid_amount, 
UNIX_TIMESTAMP(created_at) AS duration 
FROM job_card 
WHERE UNIX_TIMESTAMP(created_at) >= 1504549800 AND 
UNIX_TIMESTAMP(created_at) <= 1507055400 GROUP BY date(payment_date)

1 个答案:

答案 0 :(得分:-1)

您无法在created_at字段上使用日期功能。您需要将date转换为created_at > '2017-09-03'字段。

这将使您的SQL更加清晰,您可以直接在查询中使用YYYY-MM-DD等条款。

我不知道您的日期目前是如何格式化为字符串,但最好的选择可能是写一些内容来阅读日期,将其格式化为mysql> desc test; +--------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+-------------+------+-----+---------+-------+ | field1 | varchar(10) | YES | | NULL | | +--------+-------------+------+-----+---------+-------+ 1 row in set (0.00 sec) mysql> select * from test; +------------+ | field1 | +------------+ | 2017-01-01 | +------------+ 1 row in set (0.00 sec) mysql> alter table test modify field1 date; Query OK, 1 row affected (0.24 sec) Records: 1 Duplicates: 0 Warnings: 0 mysql> desc test; +--------+------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+------+------+-----+---------+-------+ | field1 | date | YES | | NULL | | +--------+------+------+-----+---------+-------+ 1 row in set (0.00 sec) mysql> select * from test; +------------+ | field1 | +------------+ | 2017-01-01 | +------------+ 1 row in set (0.00 sec) ,然后重新插入它们。如果所有日期都是该格式,您应该能够将该字段转换为日期类型并保持信息完整。

{{1}}