2

I have a column which value is combine two elements, Just like "Class_Name"。For example , "Websites_Google"。But for some historical reasons, there have some special value which have no "Class_" prefix, like "yahoo".

Now I need to extract the class from columns. If there is no "class_" prefix , i expect return "" . I just try SUBSTRING_INDEX functions like this:

select SUBSTRING_INDEX(column1, '_', 1) .......

It works very well when the value have "class_", but in the no "class_" situation, it return the whole value, "yahoo" return "yahoo", not the empty string which i want.

How to solve it?

3 Answers 3

2

Kindly check with the following

select case when CHARINDEX ('_', column1)>0 then SUBSTRING_INDEX(column1, '_', 1) else '' end .....
Sign up to request clarification or add additional context in comments.

Comments

1

You can use IF to check if the underscore is there:

select if(locate('_',column1)=0,'',SUBSTRING_INDEX(column1, '_', 1))
from mytable

1 Comment

Thx. It's a beautiful solution.
0

You will have to create a mysql function. Here's a working example:

DELIMITER $$

DROP FUNCTION IF EXISTS `test`.`split_class` $$
CREATE FUNCTION `test`.`split_class` (`class` varchar(25)) RETURNS varchar(25)
BEGIN

DECLARE `tmp1` varchar(25);
DECLARE `tmp2` varchar(25);
DECLARE `ret` varchar(25);

  set `tmp1` = SUBSTRING_INDEX(`class`, '_', 1);
  set `tmp2` = SUBSTRING_INDEX(`class`, '_', -1);
  set `ret` = '';

  IF `tmp1` != `tmp2`
    then set `ret` = `tmp1`;
  END IF;

  RETURN `ret`;
END $$

DELIMITER ;

Then, try the select

SELECT split_class(last) FROM test.`table` t;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.