簡體   English   中英

如何在MySQL中使用列值為表中的每個記錄生成多個記錄?

[英]How to generate multiple records for every record in a table using a column value in MySQL?

請考慮以下情形:

Area    Code    Count
BP      90-99    10
CL      78-87    10

我需要為這兩項生成十條記錄。

Area    Code
BP      90
BP      91
BP      92
BP      93
BP      94
BP      95
BP      96
BP      97
BP      98 and so on.

在oracle中,通過按級別連接可以很容易地做到這一點。 如何使用MySQL執行此操作。 請注意,第三列中確實有要進行的迭代次數,稱為count。

您需要一張數字表。 可以動態生成為派生表:

select area,
       (substring_index(code, '-', 1) + n.n - 1) as code
from (select 1 as n union all select 2 union all select 3 union all
      select 4 union all select 5 union all select 6 union all select 7 union all
      select 8 union all select 9 union all select 10
     ) n join
     scenario s
     on n.n <= s.count;

您需要確保數字列表足夠大,可以容納表中的最大數量。 如果您有可用的數字表,它會很方便。 通常, auto_increment列可以幫助生成這樣的表。

使用數字表並嘗試這種方法

Create table numbers(number int)
insert into numbers(number)
select 1 union all
select 2 union all
.
.
.
select 100

select t1.area, left(code,locate('-',code)-1)*1 from table as t1
inner join numbers as t2 on 1=1
where left(code,locate('-',code)-1)*1 +number 
<=substring(code,locate('-',code)+1,length(code))*1 

只是一個想法,您可以簡單地使用以下代碼:

CREATE TABLE #tab (area nchar(2), code nvarchar(10), count int)

INSERT INTO #tab(area, code, count)
VALUES(N'BP',N'90-99', 10),(N'CL',N'78-87',10)

SELECT *
FROM #tab t
OUTER APPLY (
        SELECT TOP(t.count) ROW_NUMBER() OVER(ORDER BY object_id) + CONVERT(int,SUBSTRING(t.code,1,PATINDEX(N'%-%',t.code)-1)) as nr 
        FROM sys.all_objects 
    ) as oa

DROP TABLE #tab

在這種情況下,我僅使用sys.all_objects來獲取一個表,以對所有內容進行編號。 您可以使用其他所有表。 如果#tab本身足夠大,可以容納足夠多的行。 另一種解決方案是使用CTE表達式生成那些需要的行。 :-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM