表[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。请高手指教

解决方案 »

  1.   

    好像要用到这个函数:replicate(character_expression,integer_expression)
      

  2.   

    use master
    select replicate(name,num)
    from a
      

  3.   

    MySQL 中,好像没有 replicate 方法吧。
    倒是有数据库复制的方法。
    不过,要是实现楼主的功能,恐怕还真的得写存储过程了,
    建议从程序中去实现。要不,就如下所示: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知道楼主看明白了没有。 
    但是,个人感觉有些傻。
      

  4.   

    我自己找到办法了另外建立一张表[B]
    里面就一个字段num
    num
    3
    3
    3
    2
    2
    1然后用
    select A.name
    from A a,B b
    where a.num=b.num这样就可以返回我要的数据了
      

  5.   

    DELIMITER $$DROP PROCEDURE IF EXISTS `test`.`sp_test`$$CREATE PROCEDURE `test`.`sp_test`()
    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 ;
      

  6.   

    create table test(name varchar(64),num int(11));
    insert into test values('tom',3),('jerry',2),('jessic',2),('lily',1);
      

  7.   

    看了看,最后感觉还是楼主 silverpearl (婷婷)   的方法不错。
    另外建立一张表[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 条记录。
      

  8.   

    只要这个数据表维护对了,数据就不会出问题,支持楼主。
    不过,个人感觉还是用程序吧。
    循环num 然后输出 name
      

  9.   

    我自己找到办法了另外建立一张表[B]
    里面就一个字段num
    num
    3
    3
    3
    2
    2
    1然后用
    select A.name
    from A a,B b
    where a.num=b.num这样就可以返回我要的数据了这个肯定会出错的 。假如有两个同为3的记录集,那么上面的语句就无法判断了。
      

  10.   

    http://blog.chinaunix.net/u/29134/showart_312707.html
      

  11.   

    数据库是用来存储数据的,它的优势不在于应用逻辑。如果有这样的需求,可以考虑用应用程序实现。
    如果要用SQL语句实现,无论什么方法,当表的量级增加很大时,都会成为瓶颈的