简体   繁体   中英

Mysql - how to sort the date format with am/pm

Please check the query.

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

I have tried this query in following cases.

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

Sample data:

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

How to do query? What's a problem in this query?

You can:

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;

Explain:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM