Sql查询以asc desc顺序选择数据,并在字符串中查找数字

时间:2015-07-03 05:21:13

标签: mysql sql

如何从带有SQL查询的字符串中找到数字,以便用asc和desc顺序选择数据?

我有表bf_offers和列title,其值如下:

title
---------------
Flat 20% off
Flat 50% off
Upto 40% off

我想找到20,50和20之类的数字。 40并以desc或asc顺序排列标题。如果我设置为desc顺序,则应按如下顺序排序数据:

title
-----------------
Flat 50% off
Flat 40% off
Upto 20% off

3 个答案:

答案 0 :(得分:2)

你可以试试 -

ORDER BY CAST(RIGHT(SUBSTRING_INDEX(title,'%',1),2) AS SIGNED) DESC

答案 1 :(得分:0)

使用substring函数执行此操作。

order by SUBSTRING(title, CHAR_LENGTH(title) - 5,2) 

或降序

order by SUBSTRING(title, CHAR_LENGTH(title) - 5,2) desc

答案 2 :(得分:0)

尝试以下,

SELECT CAST((SELECT SUBSTRING(title, n, 1)
              FROM tablename
              WHERE n <= LEN(title)
                AND SUBSTRING(titale, n, 1) LIKE '[0-9]'
              FOR XML PATH('')) AS float)
FROM tablename