MySQL:从每列返回随机值

时间:2012-12-31 03:21:09

标签: mysql

注意:这可能是一个奇怪的问题。

我有一个包含名字和姓氏的表,其格式如下(表名: random_names ):

id          INT             PRIMARY, AUTO INCREMENT
first_name  VARCHAR(100)    NOT NULL
last_name   VARCHAR(100)    NOT NULL

我想使用查询从first_namelast_name获取随机值。目前我使用2个查询来获取值:

SELECT first_name FROM random_names ORDER BY rand()
SELECT last_name FROM random_names ORDER BY rand()

但我希望我能在1个结果输出中输出随机结果列表。我错过了什么?

3 个答案:

答案 0 :(得分:3)

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到1之间的随机数,小于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;

答案 1 :(得分:1)

您可以通过以下查询以随机顺序获得所有可能的first_namelast_name对:

select *
from (select first_name from random_names) a,
     (select last_name from random_names) b
order by rand();

答案 2 :(得分:1)

您也可以这样做 -

SELECT first_name, last_name FROM random_names ORDER BY rand()

OR

SELECT concat(first_name," ",last_name) fullname FROM random_names ORDER BY rand()