简体   繁体   中英

Select values greater than a particular value in Varchar column

I have some text in a Varchar column which always ends with some numbers, for example:

abc12
xy2
asdf876
qwerty32

I need to select those values for which these numbers are greater than some number x, for example if x = 20 , the result should be:

asdf876
qwerty32

Can I do this in MySQL? Any help will be appreciated.

First of all - the need of such operation suggests that database structure was wrong from the very beginning.

You can write a function that extracts numeric sequence from a string, convert it to number and then do desired manipulations.

For example - using regular expressions(this problem has been solved for mysql using additional library).

If adding library is too difficult - you can write a function that finds first occurence of digit in string and substr's from this position to the end.

after googling I found someone who solve this with a function:

mysql> DELIMITER |
mysql> CREATE FUNCTION digits( str CHAR(32) ) RETURNS CHAR(32)
    -> BEGIN
    ->   DECLARE i, len SMALLINT DEFAULT 1;
    ->   DECLARE ret CHAR(32) DEFAULT '';
    ->   DECLARE c CHAR(1);
    ->   SET len = CHAR_LENGTH( str );
    ->   REPEAT
    ->     BEGIN
    ->       SET c = MID( str, i, 1 );
    ->       IF c BETWEEN '0' AND '9' THEN 
    ->         SET ret=CONCAT(ret,c);
    ->       END IF;
    ->       SET i = i + 1;
    ->     END;
    ->   UNTIL i > len END REPEAT;
    ->   RETURN ret;
    -> END |
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;

and to use it:

mysql> select * from t1 where actor_id > digits('ABCDefg199');
+----------+------------+-----------+---------------------+
| actor_id | first_name | last_name | last_update         |
+----------+------------+-----------+---------------------+
|      206 | a          | b         | 0000-00-00 00:00:00 |
|      200 | THORA      | TEMPLE    | 2012-05-22 15:12:26 |
+----------+------------+-----------+---------------------+
2 rows in set (0.12 sec)

source: http://www.artfulsoftware.com/infotree/queries.php?&bw=1280#815

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