MySQL return result by quantity per row -
i need query requires me return below.
data table -------------------------------- product name | quantity apple | 3 egg | 2 query expected result -------------------------------- product name apple apple apple egg egg
thanks feedback
update #1 ok bad question unclear. want display result looping product quantity. expected result on quantity makes confusion. therefore, possible loop record quantity in mysql?
if need in sql can leverage tally(numbers) table, can create , populate values 1-100 so
create table tally(n int not null auto_increment primary key); insert tally (n) select a.n + b.n * 10 + 1 n (select 0 n union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) ,(select 0 n union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) b order n;
then query
select product_name data_table d join tally t on t.n <= d.quantity
note: make sure have max(n)
value in tally
table >= max(quantity)
in data_table
work properly
output:
+--------------+ | product_name | +--------------+ | apple | | apple | | apple | | egg | | egg | +--------------+
here sqlfiddle demo
Comments
Post a Comment