简体   繁体   中英

Find/Cut string from first integer in MySQL

I'm stuck with a problem, in my database i've values like this:

GSB45-B, GSBD60-01, etc.

Now i need to get the values GSB / GSBD out of these strings. So in fact i need te first character from te start to the first integer.

Hopefully someone can help me, thanks from now.

It's a bit of a clunky solution, but you can try:

SELECT 
    REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(SUBSTRING_INDEX(column, '-', 1), '0', ''), '1', ''), '2', ''), '3', ''), '4', ''), '5', ''), '6', ''), '7', ''), '8', ''), '9', '') AS extracted
FROM
    yourtbl

How about this??

SELECT 
  myWord, 
  SUBSTR(myWord,1,LEAST (
    if (Locate('0',myWord) >0,Locate('0',myWord),999),
    if (Locate('1',myWord) >0,Locate('1',myWord),999),
    if (Locate('2',myWord) >0,Locate('2',myWord),999),
    if (Locate('3',myWord) >0,Locate('3',myWord),999),
    if (Locate('4',myWord) >0,Locate('4',myWord),999),
    if (Locate('5',myWord) >0,Locate('5',myWord),999),
    if (Locate('6',myWord) >0,Locate('6',myWord),999),
    if (Locate('7',myWord) >0,Locate('7',myWord),999),
    if (Locate('8',myWord) >0,Locate('8',myWord),999),
    if (Locate('9',myWord) >0,Locate('9',myWord),999)
  )-1) as NewString
FROM myTable;

Demo

Also read, Using alias name in another column . This is same question as yours.

DELIMITER |
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 );
  label1: LOOP
  REPEAT
    BEGIN
      SET c = MID( str, i, 1 );
      IF c BETWEEN '0' AND '9' THEN 
        SET ret=SUBSTRING( str, 1, i-1);

        LEAVE label1;
      END IF;
      SET i = i + 1;
    END;
  UNTIL i > len END REPEAT;
  END LOOP label1;
  RETURN ret;
END |
DELIMITER ;

select digits('GSB45-B'),digits('GSBD60-01') ,digits('KKGSBD60-01') ;

MySQL can't do REGEXP extraction, and that's a really sad thing :(

Assuming that the pattern of your values is [AZ]*[0-9]{2}-.* you can use this ugly thing:

SELECT
    LEFT(
        SUBSTRING_INDEX("GSB45-B", "-", 1),
        LENGTH(SUBSTRING_INDEX("GSB45-B", "-", 1)) - 2
    ) as CODE;

But I would recommand doing your parsing on the application side :)

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