gpt4 book ai didi

mysql - 如何在mysql中将单行拆分为多列

转载 作者:行者123 更新时间:2023-11-29 04:31:31 25 4
gpt4 key购买 nike

简单问一下,mysql中有没有函数可以将单行元素拆分成多列?我有一个包含字段的表行,user_id、user_name、user_location。

在此用户可以添加多个位置。我正在使用 php 分解位置并将其作为单行存储在表中。

当我在 GridView 中显示用户记录时,我遇到了分页问题,​​因为我通过拆分 user_locations 来显示记录。所以我需要拆分 user_locations(单行到多列)。

mysql有没有函数可以按字符(%)拆分和统计记录

例如 user_location 有 US%UK%JAPAN%CANADA

如何将这条记录分成 4 列。我还需要检查计数值 (4)。提前致谢。

最佳答案

首先规范化字符串,删除空位置并确保末尾有一个 %:

select replace(concat(user_location,'%'),'%%','%') as str
from YourTable where user_id = 1

然后我们可以用一个技巧来计算条目的数量。将“%”替换为“%”,并计算添加到字符串中的空格数。例如:

select length(replace(str, '%', '% ')) - length(str)
as LocationCount
from (
select replace(concat(user_location,'%'),'%%','%') as str
from YourTable where user_id = 1
) normalized

使用 substring_index,我们可以为多个位置添加列:

select length(replace(str, '%', '% ')) - length(str)
as LocationCount
, substring_index(substring_index(str,'%',1),'%',-1) as Loc1
, substring_index(substring_index(str,'%',2),'%',-1) as Loc2
, substring_index(substring_index(str,'%',3),'%',-1) as Loc3
from (
select replace(concat(user_location,'%'),'%%','%') as str
from YourTable where user_id = 1
) normalized

对于您的示例 US%UK%JAPAN%CANADA,此打印:

LocationCount  Loc1    Loc2    Loc3
4 US UK JAPAN

所以你看这是可以做到的,但是解析字符串并不是 SQL 的强项之一。

关于mysql - 如何在mysql中将单行拆分为多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1673238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com