MySQL如何使用随机数创建动态表

时间:2014-10-21 10:17:03

标签: mysql random

这是我的例子:

这是我要创建的表,(静态)

Id   Image
1     a.jpg
2     b.jpg
3     c.jpg

现在将Id作为外键我想创建一个动态表为

Rid Id
1    2
2    1
3    1
4    3
5    2 
6    3
7    3
8    2
9    2
10   1

请注意,Id是随机的。 我怎么能?

1 个答案:

答案 0 :(得分:0)

/*example table*/
create table foo(id int auto_increment primary key, rnd int);
/*now insert as much as necessary*/
/*this will create one entry*/
insert into foo(rnd)
select rand() * 2 + 1;
/*you can also use a table which has more rows than you need*/
insert into foo(rnd)
select rand() * 2 + 1 from whatever_table limit 10; /*limit it to 10 entries*/
                                                    /*or whatever           */