How can SQL create duplicate records?

前端 未结 3 657
再見小時候
再見小時候 2020-12-20 18:22

I was having a look at this question: Getting random value from a SQLite table and it got me wondering if one can duplicate records using SQL. More specifically, is there a

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-20 18:52

    You can use a "numbers" table (it's handy for various operations):

    CREATE TABLE num
    ( i UNSIGNED INT NOT NULL
    , PRIMARY KEY (i)
    ) ;
    
    INSERT INTO num (i)
    VALUES
      (1), (2), ..., (1000000) ;
    

    Then:

    SELECT 
        t.id, t.name
    FROM 
            tableX AS t
        JOIN
            num
                ON num.i <= t."count"
    

    Warning: There is of course a limitation on this approach. The query will not produce all the wanted rows, as soon as you have a value in the count column that exceeds the maximum value stored in the Numbers table. If the values in the count column are unbounded, then only an iterative or recursive solution (like the other two answers) can work.

提交回复
热议问题