2013-01-22 75 views
2

mysql查詢返回意外。我試圖串連像弦數含日期查詢,以便:連接日期函數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; 

可能有人讓我知道我做錯了嗎? ......我想如何解決這將是很好過:)

+1

'+'是[加法運算] (http://dev.mysql.com/doc/refman/5.0/en/arithmetic-functions.html#operator_plus)(但在MSSQL中用於字符串連接)。 –

回答

5

在MySQL中,使用CONCAT_WS

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

查詢,

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

或使用DATE_FORMAT

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

其他(S):

+1

太棒了!普通的'CONCAT'完美運作。忘了那些......謝謝! –

+0

@iight看到我的更新 –

2

使用CONCAT,日,月,年等格式化日期是愚蠢的。

如果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` 
... 
+0

我同意,謝謝你的幫助! –