表[A],2个字段,name,num,
数据为:
name num
tom 3
jerry 2
jessic 2
lily 1
希望通过一段SQL语句得到以下的数据集:
tom
tom
tom
jerry
jerry
jessic
jessic
lily就是根据NUM的值,重复几次NAME。请高手指教
数据为:
name num
tom 3
jerry 2
jessic 2
lily 1
希望通过一段SQL语句得到以下的数据集:
tom
tom
tom
jerry
jerry
jessic
jessic
lily就是根据NUM的值,重复几次NAME。请高手指教
select replicate(name,num)
from a
倒是有数据库复制的方法。
不过,要是实现楼主的功能,恐怕还真的得写存储过程了,
建议从程序中去实现。要不,就如下所示:select name where num = 3 union select name where num = 3 union select name where num = 3 union select name where num = 2 union select name where num = 2 union select name where num = 1 order by name
u知道楼主看明白了没有。
但是,个人感觉有些傻。
里面就一个字段num
num
3
3
3
2
2
1然后用
select A.name
from A a,B b
where a.num=b.num这样就可以返回我要的数据了
BEGIN
declare cnt int(11);
declare num1 int(11);
declare i int(11);
declare j int(11);
create temporary table num (num int(11));
select count(*) from test where 1 = 1 into cnt;
set i = 0;
loop1:loop
set @query1 = concat('select num from test limit ',i,'1 into ',num1);
prepare stmt1 from @query1;
execute stmt1;
deallocate prepare stmt1;
set j = 1;
loop2:loop
set @query2 = concat('insert into num values(',num1,')');
prepare stmt2 from @query2;
execute stmt2;
deallocate prepare stmt2;
set j = j + 1;
if j > num1 then
leave loop2;
end loop loop2;
set i = i + 1;
if i > cnt then
leave loop1;
end loop loop1;
select a.name from test a ,num b where a.num = b.num;
END$$DELIMITER ;
insert into test values('tom',3),('jerry',2),('jessic',2),('lily',1);
另外建立一张表[B]
里面就一个字段num
num
3
3
3
2
2
1不过,维护这个表有些麻烦,但是可以实现楼主的需求。
维护到5的表 表数据如下:
num
5
5
5
5
5
4
4
4
4
3
3
3
2
2
1维护到几,就需要 N*(N+1)/2 条记录。
不过,个人感觉还是用程序吧。
循环num 然后输出 name
里面就一个字段num
num
3
3
3
2
2
1然后用
select A.name
from A a,B b
where a.num=b.num这样就可以返回我要的数据了这个肯定会出错的 。假如有两个同为3的记录集,那么上面的语句就无法判断了。
如果要用SQL语句实现,无论什么方法,当表的量级增加很大时,都会成为瓶颈的