今天遇到了一个需求,有点意思
给一个用户,随机生成1-3条评论.
这些评论的内容有一个固定的范围.
用户表
create table user
(
userid int,
name varchar(10)
);
insert into user values
(1,'user1'),
(2,'user2'),
(3,'user3');
评论内容表
create table comment_template(
comment varchar(20)
);
insert into comment_template
values
('好'),
('顶'),
('赞'),
('威武'),
('支持'),
('拥护'),
('辛苦'),
('有希望了'),
('看到希望了');
首先,创建数字辅助表,
create table nums(id int not null primary key);
delimiter $$
create procedure pCreateNums(cnt int)
begin
declare s int default 1;
truncate table nums;
while s<=cnt do
insert into nums select s;
set s=s+1;
end while;
end $$
delimiter ;
call pCreateNums(1000);
然后SQL如下,
select
a.*,
(select * from comment_template order by rand() limit 1) comment
from
(
select
userid,
name,
1+round(2*rand(),0) rand
from user
) a,nums where nums.id<=a.rand;
用户表,首先生成一个1-3的随机数字,然后通过数字辅助表生成row,
最后,使用相关子查询随机获取一个评论.
结果

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