order by datetime with type varchar

时间:2016-12-09 12:58:23

标签: sql datetime sql-order-by mariadb varchar

I have a question and I didn't find the solution on stackoverflow. So here is my question:

How can I order a Varchar on datetime (dd/mm/yy hh:mm:ss) priorities in my PHP file? I have a SQL table with a "registerdate" column. Its type is Varchar (datetime isn't possible due to other table issues). My SQL ORDER BY query is:

SELECT * FROM users ORDER BY registerdate DESC LIMIT 3

This results in:

12-11-16 11:03:54 
06-12-16 19:05:22 
06-12-16 15:03:30

How I want it:

06-12-16 19:05:22
06-12-16 15:03:30
12-11-16 11:03:54

In my php file I register the time with $datetime=date("d/m/y H:i:s"); and in my table it is a Varchar who looks like 03/12/16 12:19:33

I think I have to CONVERT it in my SQL Query but I don't know how. Who can help me? Many thanks in advance!

-----SERVER/SQL INFO-----

Server: Localhost via UNIX socket
Servertype: MariaDB
Serverversie: 10.0.27-MariaDB-cll-lve - MariaDB Server
Protocolversie: 10

3 个答案:

答案 0 :(得分:0)

SELECT * FROM users u ORDER BY STR_TO_DATE(u.registerdate, '%d/%m/%Y %H:%i:%s') DESC LIMIT 3

SELECT *, STR_TO_DATE(u.registerdate, '%d/%m/%Y %H:%i:%s') as newdate FROM users u ORDER BY newdate DESC LIMIT 3 

答案 1 :(得分:0)

我认为如果你使用的是sql server,这对你也有用。

SELECT * FROM users ORDER BY Cast(registerdate AS datetime)DESC

答案 2 :(得分:0)

对于Oracle数据库,语法为:

SELECT * FROM users ORDER BY TO_DATE(registerdate,'DD / MM / YY HH24:MI:SS')DESC