mysql - 如何在 MySQL 中将逗号分隔字段扩展为多行

标签 mysql string

select id, ips from users;

查询结果

id    ips
1     1.2.3.4,5.6.7.8
2     10.20.30.40
3     111.222.111.222,11.22.33.44
4     1.2.53.43

我想运行一个产生以下输出的查询

user_id     ip
1           1.2.3.4
1           5.6.7.8
2           10.20.30.40
3           111.222.111.222
3           11.22.33.44   
4           1.2.53.43

最佳答案

如果您不介意使用光标,这里有一个示例:


set nocount on;
-- create sample table, @T
declare @T table(id int, ips varchar(128));
insert @T values(1,'1.2.3.4,5.6.7.8')
insert @T values(2,'10.20.30.40')
insert @T values(3,'111.222.111.222,11.22.33.44')
insert @T values(4,'1.2.53.43')
insert @T values(5,'1.122.53.43,1.9.89.173,2.2.2.1')

select * from @T

-- create a table for the output, @U
declare @U table(id int, ips varchar(128));

-- setup a cursor
declare XC cursor fast_forward for select id, ips from @T
declare @ID int, @IPS varchar(128);

open XC
fetch next from XC into @ID, @IPS
while @@fetch_status = 0
begin
        -- split apart the ips, insert records into table @U
        declare @ix int;
        set @ix = 1;
        while (charindex(',',@IPS)>0)
        begin
            insert Into @U select @ID, ltrim(rtrim(Substring(@IPS,1,Charindex(',',@IPS)-1)))
            set @IPS = Substring(@IPS,Charindex(',',@IPS)+1,len(@IPS))
            set @ix = @ix + 1
        end
        insert Into @U select @ID, @IPS

    fetch next from XC into @ID, @IPS
end

select * from @U

关于mysql - 如何在 MySQL 中将逗号分隔字段扩展为多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5096584/

相关文章:

regex - 从 data.frame 中选择以 R 中的特定字符串结尾的行

c# - 在 C# 中使用 mySQL 转义逗号、冒号和单引号

php - 使用透视mysql从列中动态选择值

javascript - 使用 AJAX 从 WordPress 中处理 SQL

Java字符串替换(去掉换行符,将$改为\$)

php - 如何使用 php 搜索文本 if ($text contains "World")

java - 使用 IntelliJ 中的 .sh 和 .sql 文件重新创建 MySQL 数据库

java - 在java文件中使用密码安全吗?

c# - 如何使用字符串定界符拆分字符串?

arrays - 在 golang 中将矩阵打印为字符串