0

I want to parse a text using substring. The format we have for the text is like this:

N, Adele, A, 18

And the substring we do is like this:

SUBSTRING_INDEX(SUBSTRING_INDEX(text, ',', 2), ', ', -1) as 'Name', 
SUBSTRING_INDEX(SUBSTRING_INDEX(text, ',', 4), ', ', -1) as 'Age', 

The output we get is:

|   Name    |   Age |
|   Adele   |   18  |

But we want to change the text format to:

N Adele, A 18

What would be the correct syntax so can I parse the text in the position 1 (N Adele) and use the delimiter space and just get Adele? And then same for the next text (A 18)?

I tried doing

SUBSTRING_INDEX(SUBSTRING_INDEX(text, ' ', 1), ', ', -1) as 'Name', 

But the output I got is just

|   Name    |
|   N       |

The output I was hoping for is like this:

|   Name    |
|   Adele   |
3
  • What is the desired output that you're after? Is it N Adele, A 18 or is it the same as the output you're already getting? I'm unsure. Commented Aug 13, 2014 at 23:04
  • @scrowler On the text N Adele, A 18 I want to get the output Adele and 18 Commented Aug 13, 2014 at 23:05
  • Yes that's just field names and is not important. On the text N Adele I just want to get the Adele part of that text Commented Aug 13, 2014 at 23:13

2 Answers 2

1

Presuming here that you want to change your original data structure and still be able to get the results out. You change your data structure to:

N Adele, A 18 -- etc

With the potential to have multiple names as the name (space separated), my previous example is not correct.

You could trim off the N and A directly with their space, knowing that they will only ever be two characters long and that they will always be there, like this:

SUBSTRING(TRIM(SUBSTRING_INDEX(`text`, ',', 1)), 3) AS 'Name',
SUBSTRING(TRIM(SUBSTRING_INDEX(`text`, ',', -1)), 3) AS 'Age'

To get:

Name   |   Age
--------------------
Adele  |   18
Sign up to request clarification or add additional context in comments.

2 Comments

Ah wait, what if the text is like N Adele Gaga is it still going to give the output Adele Gaga ?
Use @leon's answer - his is better. I've added another example for you anyway though.
1

You can use

SELECT
  SUBSTRING(text, 2, INSTR(text, ',') - INSTR(text, ' ')) AS Name,
  SUBSTRING(text, INSTR(text, ',') + 3, LENGTH(text) - INSTR(text, ',') + 3) AS Age
FROM your_table;

as the position of the field descriptors (N and A) are fixed (relative to the start of the string and to the comma). You can check the working query in this fiddle.

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.