简体   繁体   中英

Sort Date in Mysql table in DESC order

我想按DESC顺序显示日期列,其中日期输入为VARCHAR,顺序为2007年6月20日,我已经使用过ORDER BY RIGHT(vPublishedDate,4),但是它不影响月份和日期

Why are you using a VARCHAR to store a DATE ? Use a DATE to store a DATE and then, as if by magic, sorting works all on its own.

Here is one way to do it using STR_TO_DATE (take into account the other answers about converting the column to date, although you may not have control over the database):

SELECT ...
FROM ...
ORDER BY STR_TO_DATE(vPublishedDate,'%d-%M-%Y')

As an example:

SELECT STR_TO_DATE('20-JUN-2007','%d-%M-%Y') as Date;
+------------+
| Date       |
+------------+
| 2007-06-20 |
+------------+

You really should be storing dates as dates, not character-type fields. Then you wouldn't need to worry about this sort of "SQL gymnastics" (as I like to call it).

Databases are for storing data, not formatting.

By forcing yourself to manipulate sub-columns, you basically prevent the database from performing any useful optimisations.

In order to do what you want with the data you have you have to do something like:

  • use substring to extract individual sub-column information to get them in the order you want; and
  • use some sort of lookup to turn a string like "NOV" into 11 (since the month names will sort as DEC, FEB, AUG, APR, JAN, JUL, JUN, MAR, MAY, NOV, OCT, SEP).

And this would be a serious performance killer. Now there may be a function which can turn that particular date format into a proper date but I urge you: don't use it.

Set up or change your database to use an intelligent schema and all these problems will magically disappear.

It's a lot easier to turn a date column into any sort of output format than to do the same with a character column.

Change that VARCHAR to a Date type column, if you can.

You can also try this, although this is NOT the RIGHT approach.

Select STR_TO_DATE(your_date_column,'%d/%m/%Y') AS your_new_date from your_table order by your_new_date DESC

尝试使用str_to_date将varchar转换为date,然后可以应用排序逻辑。

I would suggest you to change the type as Date. Then run a script which converts your dates to the correct DB format.

Sorting would be then be just as simple as sorting ids in MySql

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