问题
So unfortunately I have a VARCHAR column of dates formatted like so: Jun-13-2013
(I understand that this is done incorrectly and should be stored in a DATETIME column in the standard format)
I'm trying to grab all the data in every row and ORDER by that VARCHAR column as a DATETIME, but I'm not finding anything out there to convert my poorly formatted date column for sorting.
here is my query:
$result = mysql_query("SELECT * FROM archive ORDER BY crapdates DESC");
But I'm trying to convert the crapdates
column to a datetime... is this even possible?
I'm not finding a mmm-dd-yyyy format conversion anywhere
Thanks for checking it out
回答1:
You want the STR_TO_DATE() function to convert your existing varchar column to a date value.
I'd definitely recommend creating a new column and using STR_TO_DATE()
to copy the value from your existing column into the new column, rather than using STR_TO_DATE()
directly in the ORDER BY
of your SELECT
.
UPDATE archive SET newdate = STR_TO_DATE(crapdate,'%b-%e-%Y');
If you can't change the table structure, you can sort on the existing column like this:
SELECT * FROM archive ORDER BY STR_TO_DATE(crapdate,'%b-%e-%Y') DESC;
回答2:
"You can use STR_TO_DATE() to convert your strings to MySQL date values and ORDER BY
the result:
ORDER BY STR_TO_DATE(datestring, '%d/%m/%Y')
However, you would be wise to convert the column to the DATE
data type instead of using strings."
Answer: https://stackoverflow.com/a/10637668/1146492 by xdazz
来源:https://stackoverflow.com/questions/17093417/mysql-order-by-varchar-date-in-mmm-dd-yyyy