2011-08-13 16 views
2

私はこのようなMySQLのテーブルました:mysqlの行が指定された時間だけ繰り返す方法は?

-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| id (int primary key) | count (int) |
-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

は、このテーブルは、これらの値で満たされていると仮定します

1,1
2,2
3,2
4,3
私のようにすべての行を繰り返し、このテーブルのビューを作成する必要がありますたとえば、上記のデータの場合、ビューには次の情報が含まれます。
1,1
2,1
2,2
3,1
3,2
4,1
4,2
4,3

+0

データベース内でこれを行うのは面倒かもしれません... SQL以外のプレゼンテーション層でやってください。 – TMS

答えて

0
drop table if exists my_test; 

create table my_test (
id int not null auto_increment primary key, 
`count` int) 
engine = myisam; 

insert into my_test (`count`) values (1),(2),(2),(3); 

delimiter // 
drop procedure if exists recurrences // 
create procedure recurrences() 
begin 
declare a,b int; 
declare i int default 1; 
declare finite int default 0; 
declare curs cursor for select id,`count` from my_test; 
declare continue handler for not found set finite = 1; 
drop table if exists tmp; 
create temporary table tmp (id int,cnt int); 
open curs; 
my_loop:loop 
fetch curs into a,b; 
if finite = 1 then 
leave my_loop; 
end if; 
while i <= b do 
insert into tmp (id,cnt) values (a,i); 
set i = i + 1; 
end while; 
set i = 1; 
end loop; 
close curs; 
select * from tmp; 
end // 
delimiter ; 

call recurrences(); 


+------+------+ 
| id | cnt | 
+------+------+ 
| 1 | 1 | 
| 2 | 1 | 
| 2 | 2 | 
| 3 | 1 | 
| 3 | 2 | 
| 4 | 1 | 
| 4 | 2 | 
| 4 | 3 | 
+------+------+ 
8 rows in set (0.44 sec) 

私が思った最初のことですが、実行時間が嫌いです。 ;)

+0

あなたの答えをありがとうが、私は言ったように私は見るためには保存されていない手順が必要です! –

+0

私は、ストアドプロシージャ内でビューを作成しなければ可能ではないと思います。 –

関連する問題