Mysql字符串/数字顺序

时间:2012-06-21 15:46:40

标签: mysql

您好我有一个索引字符串字段,可以包含字符串或数字。 我想得到这个索引的最大值和最小值,但我想要一个唯一的DIGITS索引是整数,否则作为字符串。 例如,我想:

   ( "1", "5", "10" )       MIN=1 MAX=10 // mind MAX=10 not 5 as string order!
   ( "A", "D", "Z" )        MIN=A MAX=Z

我试过了:

MAX(IF(CAST(idxfield as UNSIGNED)=0,CAST(idxfield as UNSIGNED),idxfield)) as maxField

但是不起作用。

2 个答案:

答案 0 :(得分:0)

您可以使用REGEXP来测试该字段是否为数字。

例如:

select '1'  REGEXP '^[0-9]+$'; // returns 1
select 'A'  REGEXP '^[0-9]+$'; // returns 0

答案 1 :(得分:0)

试试这个::

Select 
idxfield REGEXP '[0-9] as field1,
CASE field1
 WHEN 1 THEN SELECT idxfield from table order by idxfield+0 desc
 WHEN 0 THEN SELECT idxfield from table order by idxfield desc
END as max_value,
CASE field1
 WHEN 1 THEN SELECT idxfield from table order by idxfield+0
 WHEN 0 THEN SELECT idxfield from table order by idxfield
END as min_value
from table