在选择查询中将模式字符串拆分为列

时间:2018-03-04 07:41:27

标签: mysql mariadb

我有一个person表,结构如下。

CREATE TABLE person(id integer, details LONGTEXT);
INSERT INTO person(id,details) 
VALUES
(1, "name:Tahir,age:30,sex:male"),
(2, "name:Tina,sex:female,status:1");

问题: 我对db end有一些限制,无法添加新的表/列,因此必须使用LONGTEXT详细信息的可用列进行即兴创作。所以,除了其他方法,我找到了解决方法。

所以,我想用逗号分割详细信息列,并在差异列中显示结果。就像,在这个例子中,结果将是id,姓名,年龄,性别,状态

我相信聚合函数可以实现,我尝试生成如下所示的查询

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`,
if(person.details like '%status:%',cast(substring_index(substring_index(person.details,'status:',-1),',',1) as unsigned),null) as `status`
FROM person

上面的查询正确地为年龄提取数据但名称和性别得到0.你能不能弄明白我在这里缺少什么?

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

1 个答案:

答案 0 :(得分:1)

您将明显的字符串转换为无符号(整数)。无需投射:

SELECT
  id,
  if(person.details like '%name:%',substring_index(substring_index(person.details,'name:',-1),',',1),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:%',substring_index(substring_index(person.details,'sex:',-1),',',1),null) as `sex`
FROM person