Search code examples
mysqlsqlmultiple-records

Duplicating rows in one select MySql query


At first I would like greet all Users and apologize for my english :). I'm new user on this forum. I have a question about MySQL queries. I have table Items with let say 2 columns for example itemsID and ItemsQty.

itemsID ItemsQty
11  2
12  3
13  3
15  5
16  1

I need select itemsID but duplicated as many times as indicated in column ItemsQty.

itemsID ItemsQty
11  2
11  2
12  3
12  3
12  3
13  3
13  3
13  3
15  5
15  5
15  5
15  5
15  5
16  1

I tried that query:

SELECT items.itemsID, items.itemsQty

FROM base.items 

LEFT OUTER JOIN 
(

  SELECT items.itemsQty AS Qty FROM base.items

) AS Numbers ON items.itemsQty <=Numbers.Qty

ORDER BY items.itemsID; 

but it doesn't work correctly. Thanks in advance for help.


Solution

  • SQL answer - Option 1

    You need another table called numbers with the numbers 1 up to the maximum for ItemsQuantity

    Table: NUMBERS
    
    1
    2
    3
    4
    5
    ......
    max number for ItemsQuantity
    

    Then the following SELECT statement will work

    SELECT ItemsID, ItemsQty
    FROM originaltable
    JOIN numbers
        ON originaltable.ItemsQty >= numbers.number
    ORDER BY ItemsID, number
    

    See this fiddle -> you should always set-up a fiddle like this when you can - it makes everyone's life easier!!!

    code answer - option 2

    MySQL probably won't do what you want 'cleanly' without a second table (although some clever person might know how)

    What is wrong with doing it with script?

    Just run a SELECT itemsID, ItemsQty FROM table

    Then when looping through the result just do (pseudo code as no language specified)

    newArray = array();  // new array
    
    While Rows Returned from database{ //loop all rows returned
    
        loop number of times in column 'ItemsQty'{
    
              newArray -> add 'ItemsID'
    
    
        }
    
    
    }//end of while loop
    

    This will give you a new array

    0 => 11
    
    1 => 11
    
    2 => 12
    
    3 => 12
    
    4 => 12
    
    5 => 13
    

    etc.