Mysql
 sql >> Cơ Sở Dữ Liệu >  >> RDS >> Mysql

Cách mở rộng trường được phân tách bằng dấu phẩy thành nhiều hàng trong MySQL

Nếu bạn không phiền khi sử dụng con trỏ, đây là một ví dụ:


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


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. MySQL INSERT IF (câu lệnh if tùy chỉnh)

  2. Tự động tăng sau khi xóa trong MySQL

  3. Mô phỏng mã hóa mật khẩu () của MySql bằng .NET hoặc MS SQL

  4. Kết quả nhóm MySQL theo khoảng thời gian

  5. Cách mã hóa (utf8mb4) bằng Python