0

I have a person table with below structure.

CREATE TABLE person(id integer, details text);
INSERT INTO person(id,details) VALUES(1, "name:Tahir,age:30,sex:male");

I want to split details column by comma and show results in difference columns. Like, in this example result would be id, name,age, sex

I believe that is possible with aggregate functions and I tried to produce a query like below

SELECT id,
if(person.details like '%name:%',cast(substring_index(substring_index(person.details,'name:',-1),',',1) as unsigned),null) as `name`,
if(person.details like '%age:%',cast(substring_index(substring_index(person.details,'age:',-1),',',1) as unsigned),null) as `age`,
if(person.details like '%sex:%',cast(substring_index(substring_index(person.details,'sex:',-1),',',1) as unsigned),null) as `sex`
FROM person

above query fetches data correctly for age but name and sex gets 0. Could you please figure out what I am missing here?

https://www.db-fiddle.com/f/cqyqb7Vhvs7kKYifFywmkV/6

3
  • Why are you placing all these values into a single column in 1st place? Mar 3, 2018 at 17:24
  • @πάνταῥεῖ I have some limitations on db end, can't add new tables/columns so have to improvise with available column that is LONGTEXT details. So, I have no other way but find a workaround. Mar 4, 2018 at 7:24
  • Don't put the data together if you need to work with it split apart. Or do the split in your app code.
    – Rick James
    Mar 7, 2018 at 19:13

2 Answers 2

1

Does this cover your expected result?

SELECT SUBSTRING_INDEX(name, ':', -1) name,
       SUBSTRING_INDEX(age, ':', -1) age,
       SUBSTRING_INDEX(sex, ':', -1) sex
FROM (SELECT SUBSTRING_INDEX(details, ',', 1) name,
             SUBSTRING_INDEX(SUBSTRING_INDEX(details, ',', 2), ',', -1) age,
             SUBSTRING_INDEX(details, ',', -1) sex
      FROM   person) t;
name  | age | sex 
:---- | :-- | :---
Tahir | 30  | male

dbfiddle here

1
  • thanks for the answer but it works fine with the fixed pattern but will not work with dynamic details. For example, if another key:value pair is attached it will not recognize that. Do you think it can be made dynamic to recognize all key:value pairs? Mar 4, 2018 at 7:17
0

Your column is quite like JSON, so perhaps:

select
  json_value(j,'$.name') name,
  json_value(j,'$.age') age,
  json_value(j,'$.sex') sex
  from (select concat('{',
                      regexp_replace(details,
                                     '([a-z]+):([a-z0-9]+)(,?)',
                                     '"\\1":"\\2"\\3'),
                      '}') J from person) p;

I've run this on an up to date MariaDB, but MySQL wants nothing to do with it (no regexp_replace).

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.