使用Order By当字符串由数字和字母组成时,仅按数字排序

时间:2012-10-24 13:07:38

标签: php mysql

我有一个列,我需要排序,其中包含按字母顺序排列的字符和数字

现在有以下值

ABC223 ABC12

现在我只需要忽略字符串中的字母字符

的数字来排序

要记住的东西有时候价值可以从GD开始,其他只有A有时123AB et

这一切都可能吗?

3 个答案:

答案 0 :(得分:2)

你可以这样做:

ORDER BY SUBSTRING(YourColumn, 3)

答案 1 :(得分:1)

查看:https://launchpad.net/mysql-udf-regexpHow to do a regular expression replace in MySQL?

如果您使用udf,则可以使用正则表达式替换执行ORDER BY。

答案 2 :(得分:0)

您可以使用uasort对包含该值的数组进行排序。

例如:

$pattern = "/\d+/";
$values = array('ABC123', 'ABC12', 'GD44'); //Just for example

uasort($values, function ($a, $b) use ($pattern)
   {
       $matches = array();
       preg_match($pattern, $a, $matches);
       $a = $matches[0];
       preg_match($pattern, $b, $matches);
       $b = $matches[0];

       return $a - $b;
   });

var_dump($values);

此外,您可以使用udf来使用sql查询来操纵regex