select
(select first_name from random_names order by rand() limit 1) as random_first_name,
(select last_name from random_names order by rand() limit 1) as random_last_name;
虽然对于任何大小的表,如果您以编程方式确定条目数并为每列选择一个随机偏移量,它会更快:
select
(select first_name from random_names order by rand() limit $first_name_offset,1) as random_first_name,
(select last_name from random_names order by rand() limit $last_name_offset,1) as random_last_name;
其中偏移量是从 0 到比 的结果小一的随机数select count(*) from random_names
。
后续问题:
但是如何列出结果计数等于原始表中的值的数量?(就像打乱表中的数据一样)
我会这样做:
create temporary table rand_last (id int(11) primary key auto_increment, last_name text) select last_name from random_names order by rand();
create temporary table rand_first (id int(11) primary key auto_increment, first_name text) select first_name from random_names order by rand();
select first_name, last_name from rand_first inner join rand_last using (id);
或者可能像这样(假设 random_names 有一个 'id' 主键):
create temporary table rand_one (id int(11) primary key auto_increment, random_names_id int(11)) select id random_names_id from random_names order by rand();
create temporary table rand_two (id int(11) primary key auto_increment, random_names_id int(11)) select id random_names_id from random_names order by rand();
select rand_first.first_name, rand_last.last_name from rand_one inner join rand_two using (id) inner join random_names rand_first on rand_one.random_names_id=rand_first.id inner join random_names rand_last on rand_two.random_names_id=rand_last.id;