2

mysql 查询返回意外。我正在尝试连接一些包含日期查询的字符串,如下所示:

mysql> select month(timestamp) +'-'+ day(timestamp) + '-' + 
       year(timestamp) as date FROM table ORDER BY timestamp DESC LIMIT 1;

我得到一个 4 位数的结果,我认为这是预期结果的总和:

+------+
| date |
+------+
| 2035 |
+------+

我也尝试过将每个都设置为CHAR不起作用:

mysql> select CAST(month(timestamp) as CHAR) +'-'+ CAST(day(timestamp) as CHAR) + '-' + 
CAST(year(timestamp) as CHAR) as date FROM table ORDER BY timestamp DESC LIMIT 1;

有人可以让我知道我做错了什么吗?...我想如何解决它也会很好:)

4

2 回答 2

5

In MySQL, use CONCAT_WS

CONCAT_WS('-', month(timestamp),day(timestamp),year(timestamp))

query,

SELECT CONCAT_WS('-', month(timestamp),day(timestamp),year(timestamp)) AS DATE
FROM   tablename
ORDER  BY timestamp DESC 
LIMIT  1

or use DATE_FORMAT

SELECT DATE_FORMAT(timestamp, '%m-%d-%Y') AS DATE
FROM   Table1
ORDER  BY timestamp DESC 
LIMIT  1

Other(s):

于 2013-01-22T08:06:37.383 回答
2

使用 CONCAT、DAY、MONTH、YEAR 等来格式化日期是愚蠢的。

如果timestamp是包含 UNIX 时间戳的整数列,请使用:

SELECT DATE_FORMAT(FROM_UNIXTIME(`timestamp`), '%m-%d-%Y') AS `Formatted Date`
...

如果timestamp是日期/日期时间列,请使用:

SELECT DATE_FORMAT(`timestamp`, '%m-%d-%Y') AS `Formatted Date`
...
于 2013-01-22T08:13:03.823 回答