mysql - CAST(日期 AS DATE) 日期格式

标签 mysql date casting

我有以下 php 例程来从表中提取值。我正在尝试将 DATE 类型从“2014-08-10”值转换为“20140810”值

返回时间:

//query
$query = mysql_query("SELECT CAST(date AS DATE), EtotalDay from MonthData group by 1 order by 1") 
OR die ('Query is invalid: ' . mysql_error());

//write the results
while ($row = mysql_fetch_array($query)) {echo  $row['CAST(date AS DATE)'] . "," . $row['EtotalDay'] . "\n";

我怎样才能做到这一点?

最佳答案

你应该使用

DATE_FORMAT(date, '%Y%m%d')

代替 CAST(),使用列别名来完成字段检索

$query = mysql_query("SELECT DATE_FORMAT(date, '%Y%m%d') formattedDate, EtotalDay from MonthData group by 1 order by 1") or die ('Query is invalid: ' . mysql_error());


//write the results
while ($row = mysql_fetch_array($query)) {echo  $row['formattedDate'] . "," . $row['EtotalDay'] . "\n";

参见手册,DATE_FORMAT

DATE_FORMAT(date,format)

Formats the date value according to the format string.

The following specifiers may be used in the format string. The “%” character is required before format specifier characters.

%d Day of the month, numeric (00..31)
%m Month, numeric (00..12)
%Y Year, numeric, four digits

关于mysql - CAST(日期 AS DATE) 日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25314345/

相关文章:

mysql - 仅按来自左连接查询的那部分排序

php - 我什么时候必须关闭 mysqli(数据库)连接?

java - 无法在数据库中保存日期(月/日/年)

c++ - 如何在不获取未定义行为的情况下重新解释或转换具有已知内存布局的对象

php - 将自动递增的变量名插入数据库

php - 新闻评论数

ruby-on-rails - 用 ruby 显示日期

java - 持续时间或间隔中的 Joda Time 分钟数

c++ - "bitwise or"有时工作

c - 我该怎么做才能停止错误 "expected expression before ‘char’“?