MySQL 基于 round(1 + rand() * x) 的查找产生 NULL 和多个结果

MySQL lookup based on round(1 + rand() * x) produces NULL and multiple results

我正在尝试 select 从 MySQL 中随机查找 table 的名字来构建测试数据集。我有一个 table,有 200 个名字、性别和一个从 1 到 200 的行 ID。像这样:

id   firstname   gender
1    Aaron       m
2    Adam        m
3    Alan        m
etc...

我正在 select 使用带有以下查询的 random generator 从这个 table 开始:

SELECT id, firstname FROM firstname WHERE id = round(1 + (rand() * 199));

我期望随机数与查找中的一个 ID 完全一致 table,从而产生一个结果,如

id   firstname
43   Jason

运行 代码一次又一次地给了我一个 selection of

id firstname 29 Ethan 147 Jean

如果我 运行 随机生成器本身,它将始终生成 1 到 200 之间的数字。正如您在下面看到的,id 字段是 INT,查询的行为方式相同,如果我将结果投射为 SIGNED。我还尝试使用 FLOOR 而不是 ROUND,只是想看看它是否有任何不同 - 唉,没有。

谁能告诉我为什么会出现异常?我错过了什么?

下面是一些代码,用于创建原始 table 的前 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");

由于 RAND() 不是确定性的,WHERE 条件是每行一次 evaluated/executed。因此每一行都有 1/199 的机会被选中。您可以在 FROM 子句中使用子查询(派生 table)来生成恰好一个随机数:

SELECT f.id, f.firstname
FROM firstname f
JOIN (SELECT floor(rand()*200)+1 as rnd) r ON r.rnd = f.id