ITPub博客

首页 > 数据库 > MySQL > MySQL数字辅助表

MySQL数字辅助表

原创 MySQL 作者:壹頁書 时间:2014-12-10 10:46:57 2 删除 编辑
最近在做一个活动签到的功能,每个用户每天签到,累计到一定次数,可以换一些奖品。
签到表的设计如下

  1. CREATE TABLE `award_chance_history` (
  2.   `id` int(11) NOT NULL AUTO_INCREMENT,
  3.   `awardActId` int(11) DEFAULT NULL COMMENT '活动id',
  4.   `vvid` bigint(20) DEFAULT NULL COMMENT '用户id',
  5.   `createtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '签到时间',
  6.   `reason` varchar(40) DEFAULT NULL COMMENT '事由',
  7.   `AdditionalChance` int(11) DEFAULT '0' COMMENT '积分变动',
  8.   `type` int(11) DEFAULT NULL COMMENT '类型',
  9.   `Chance_bak` int(11) DEFAULT '0',
  10.   PRIMARY KEY (`id`)
  11. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

到了测试的阶段,问题来了。
测试需要让我做一批数据,模拟用户签到了20天,30天..以便测试.
这在Oracle都不是事儿,用Connect By直接可以解决.
但是MySQL没有这个功能,
一开始,我是这么做的


这种场景其实可以用数字辅助表的方式,在MySQL技术内幕(SQL)中有记录
首先,创建数字辅助表

  1. create table nums(id int not null primary key);

  2. delimiter $$
  3. create procedure pCreateNums(cnt int)
  4. begin
  5.     declare s int default 1;
  6.     truncate table nums;
  7.     while s<=cnt do
  8.         insert into nums select s;
  9.         set s=s+1;
  10.     end while;
  11. end $$
  12. delimiter ;

  13. delimiter $$
  14. create procedure pFastCreateNums(cnt int)
  15. begin
  16.     declare s int default 1;
  17.     truncate table nums;
  18.     insert into nums select s;
  19.     while s*2<=cnt do
  20.         insert into nums select id+s from nums;
  21.         set s=s*2;
  22.     end while;
  23. end $$
  24. delimiter ;
初始化数据
call pFastCreateNums(10000);

创建测试数据
  1. insert into award_chance_history(awardactid,vvid,reason,additionalChance,type,createtime)
  2. select 12,70021346,'手机签到测试',10,2,date_add('2014-12-14',interval id day) from nums order by id limit 10;
这样就创建了从 2014-12-15以后的连续10天签到数据.


方便多了..

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-1362897/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2013-10-19

  • 博文量
    620
  • 访问量
    6339932