Sort longtext as int in SQL

空扰寡人 提交于 2019-12-07 17:44:09

问题


I have table in MySQL database where one column type is longtext and there are stored numbers. I need to get content from table sorted by numbers in that column.

SELECT * FROM wp_postmeta WHERE meta_key = 'rating_avg' ORDER BY meta_value

With this query sorting is not proper and looks like:

0
1.6
10
5

but I need like this:

10
5
1.6
0

I may not change column type, because this column have many different types of data. Is there any possibility to change column type temporary in SQL query?


回答1:


What you are looking for is CAST.

CAST(expr AS type)

Your SQL Query should look like this:

SELECT * FROM wp_postmeta WHERE meta_key = 'rating_avg' ORDER BY CAST(`meta_value` AS DECIMAL) DESC



回答2:


This can also be accomplished through native WordPress functions without having to resort to raw SQL. Give WP_Query an orderby parameter of meta_value_num rather than meta_value (reference).




回答3:


It's been over a year since the question was asked, but for reference to anyone that came here after the search, the answer is

CAST(meta_value AS DECIMAL(10,2))

so the query should be:

SELECT * FROM wp_postmeta WHERE meta_key = 'rating_avg' ORDER BY CAST(`meta_value` AS DECIMAL(10,2)) DESC


来源:https://stackoverflow.com/questions/8865081/sort-longtext-as-int-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!