我尝试在mysql中随机从查找表中选择名字来构建测试数据集。我有一个表,有200个名字,性别和行id从1到200。像这样:
id firstname gender
1 Aaron m
2 Adam m
3 Alan m
etc...
我使用随机生成器从该表中选择以下查询:
SELECT id, firstname FROM firstname WHERE id = round(1 + (rand() * 199));
我希望随机数与查找表中的一个id相加,从而生成一个结果,如
id firstname
43 Jason
一次又一次地运行代码会给我一个
单行(同上)
或多行,如 id firstname 29 Ethan 147 Jean
或者没有结果(两个字段都为空)。
如果我自己运行随机生成器,它将始终生成1到200之间的数字。正如您在下面看到的,id字段是int,如果将结果强制转换为signed,查询的行为与此相同。我也试过用地板代替圆形,只是想看看效果是否有什么不同——唉,没有。
有人能告诉我为什么会出现这种异常吗?我错过了什么?
以下是一些代码,用于创建原始表的前20行以进行测试:
-- First Name --
drop table if exists firstname;
CREATE TABLE firstname (
id INT NOT NULL,
firstname VARCHAR(20) NOT NULL,
gender VARCHAR(1) NOT NULL,
PRIMARY KEY (id),
UNIQUE (firstname)
);
INSERT INTO firstname
(id,firstname,gender)
VALUES
(1,"Aaron","m"),
(2,"Adam","m"),
(3,"Alan","m"),
(4,"Albert","m"),
(5,"Alexander","m"),
(6,"Andrew","m"),
(7,"Anthony","m"),
(8,"Arthur","m"),
(9,"Austin","m"),
(10,"Benjamin","m"),
(11,"Billy","m"),
(12,"Bobby","m"),
(13,"Brandon","m"),
(14,"Brian","m"),
(15,"Bruce","m"),
(16,"Bryan","m"),
(17,"Carl","m"),
(18,"Charles","m"),
(19,"Christian","m"),
(20,"Christopher","m");
1条答案
按热度按时间dsekswqp1#
自
RAND()
不是确定性的,where条件每行计算/执行一次。因此,每行有1/199的机会被选中。您可以使用from子句(派生表)中的子查询来生成一个随机数: