數字輔助表應用一則(分組生成行)

壹頁書發表於2015-03-31
今天遇到了一個需求,有點意思

給一個使用者,隨機生成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部落格 ” ,連結:http://blog.itpub.net/29254281/viewspace-1480798/,如需轉載,請註明出處,否則將追究法律責任。

相關文章