【问题标题】:How to expand comma-separated field into multiple rows in MySQL如何在 MySQL 中将逗号分隔的字段扩展为多行
【发布时间】:2011-02-23 20:19:16
【问题描述】:
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

【问题讨论】:

  • 我希望你喜欢使用临时表和 SPROC。有些东西告诉我这个数据库需要标准化——完全不同。
  • 如果可以,重新设计数据库的这一部分,使其标准化。 user_id 到 ip 的 1:n 关系应该存储在自己的表中。
  • @Brad Christie,数据库一般没问题。这是我遇到过的一次性标准化问题。

标签: mysql string


【解决方案1】:

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


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

【讨论】:

    【解决方案2】:

    我不认为这是您想要使用查询执行的操作,但您更愿意在您的演示逻辑中执行此操作。数据库仅用于存储和检索数据。格式化数据并呈现它是在你的表现层中做的事情,通常与 PHP/ASP.NET/其他东西结合使用。

    【讨论】:

      【解决方案3】:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-31
        • 2014-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多