2

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

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

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

我想使用查询从first_name和中获取随机值last_name。目前我使用 2 个查询来获取值:

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

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

4

3 回答 3

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 到比 的结果小一的随机数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;
于 2012-12-31T03:30:39.827 回答
1

你也可以这样做-

SELECT first_name, last_name FROM random_names ORDER BY rand()

或者

SELECT concat(first_name," ",last_name) fullname FROM random_names ORDER BY rand()
于 2012-12-31T03:47:41.087 回答
1

您可以通过以下查询以随机顺序获取所有可能的对first_name和:last_name

select *
from (select first_name from random_names) a,
     (select last_name from random_names) b
order by rand();
于 2012-12-31T03:36:36.357 回答