2013-08-01 30 views
1

請檢查查詢。Mysql - 如何使用am/pm排序日期格式

SELECT DATE_FORMAT(CAST(CONCAT(table.date, " ", table.time)) , '%p') 
FROM table AS table 

Error: 
[hash]1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '), '%p') FROM exp_visitorsday as vd LIMIT 0, 30' at line 2 

我在以下情況下試過這個查詢。

SELECT DATE_FORMAT(CAST(CONCAT(table.date, " ", table.time) as datetimecol) as datetimecol, '%p') 
FROM table AS table 

SELECT DATE_FORMAT(CAST(CONCAT(table.date, " ", table.time) as datetimecol), '%p') 
FROM table AS table 

的樣本數據:

table.date => 01-08-2013 
table.time => 10:00 AM 

怎麼辦查詢?這個查詢有什麼問題?

+3

'CAST(CONCAT(table.date, 「」,table.time))'...投的是什麼? –

+0

感謝Joachim。投入一段時間。我在查詢中犯了一個錯誤。我會改變並檢查它。 – user2003356

回答

1

您可以:

SELECT * 
FROM (
    SELECT DATE_FORMAT( 
            CONCAT(SUBSTRING_INDEX("01-08-2013", "-", -1), "-", 
            SUBSTRING_INDEX(SUBSTRING_INDEX("01-08-2013", "-", 2), "-", -1), "-", 
            SUBSTRING_INDEX("01-08-2013", "-", 1), " ", 
            IF(SUBSTRING_INDEX("10:00 PM", " ", -1) = "AM", 
               SUBSTRING_INDEX("10:00 AM", " ", 1), 
               CONCAT(SUBSTRING_INDEX(SUBSTRING_INDEX("10:00 AM", " ", 1), ":", 1) + 12, ":", SUBSTRING_INDEX(SUBSTRING_INDEX("10:00 AM", " ", 1), ":", -1)) )) , '%Y-%m-%d %h:%i') AS datformat) AS tmp 
ORDER BY tmp.datformat; 

解釋:

SELECT SUBSTRING_INDEX("01-08-2013", "-", 1); #Day 
SELECT SUBSTRING_INDEX(SUBSTRING_INDEX("01-08-2013", "-", 2), "-", -1);#Month 
SELECT SUBSTRING_INDEX("01-08-2013", "-", -1); #Year 
+0

謝謝GaCon。我用這個查詢來做。但我失敗了。你能檢查一下嗎? – user2003356

+0

是的,我檢查過,它運行。什麼是錯誤?你能發佈嗎? – GaCon

+0

謝謝GaCon。查詢很好。我有一個無效的數據與數據庫。完美!!! ...好工作..前進! – user2003356