我有一个具有以下结构的 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");
问题: 我对数据库端有一些限制,无法添加新表/列,因此必须临时使用 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。您能弄清楚我在这里缺少什么吗?
最佳答案
您正在将明显的字符串转换为无符号(整数)。无需转换:
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
关于mysql - 将模式字符串拆分为选择查询中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49093131/