Question

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.

Was it helpful?

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.

OTHER TIPS

Select DISTINCT 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;

Use DISTINCT to remove duplicates. Read more here - http://dev.mysql.com/doc/refman/5.0/en/select.html

It seems like I understood what you asked differently than everyone else so I hope I answer you question. What I would basically do is -

  1. create a new table for those changes.
  2. Create a mysql procedure which given a line in the original table add new lines to the new table - http://dev.mysql.com/doc/refman/5.6/en/loop.html
  3. Run this procedure for each line in the original table.

try this to get distinct values from both columns

SELECT DISTINCT itemsID FROM items
UNION 
SELECT DISTINCT itemsQty FROM items
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top