gpt4 book ai didi

MySQL : Return random value from each column

转载 作者:行者123 更新时间:2023-11-29 01:30:40 25 4
gpt4 key购买 nike

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

我有一个包含名字和姓氏的表,其架构如下(表名: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 个结果输出中输出随机结果列表。我错过了什么?

最佳答案

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 的结果小一的随机数。

后续问题:

but how about list out result count equal to the number of values in original table? (just like shuffle the data in the table)

我会这样做:

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;

关于MySQL : Return random value from each column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14097072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com