为mysql生成特定的随机数

时间:2016-11-04 03:28:00

标签: mysql sql

您好我正在做一个问题的程序,但这个问题需要不同的用户现在我需要在mysql中随机生成问题尝试使用RAND()但我不能使这个工作正常我的工作要求,这不起作用:

SELECT * FROM oscuro.answers
INNER JOIN questions ON answers.question_id = questions.id
INNER JOIN sub_categories ON questions.sub_category_id = sub_categories.id
WHERE sub_categories.category_id = 1 AND questions.id > RAND();

我需要questions.id表格问题上所有记录的随机数字,这应该随机提出问题的所有答案。我如何仅为该字段生成随机数?

1 个答案:

答案 0 :(得分:0)

您可以在子查询上进行连接。一个简单的例子:

> SELECT * FROM `foo`;
+----+
| id |
+----+
|  1 |
|  2 |
|  3 |
|  4 |
|  5 |
+----+
> SELECT * FROM foo 
>   INNER JOIN 
>   (SELECT RAND() as random_number)
>     as sqy;

+----+---------------------+
| id | random_number       |
+----+---------------------+
|  1 | 0.16365532499147142 |
|  2 | 0.16365532499147142 |
|  3 | 0.16365532499147142 |
|  4 | 0.16365532499147142 |
|  5 | 0.16365532499147142 |
+----+---------------------+

那么在你的情况下

> SELECT * FROM oscuro.answers
>   INNER JOIN questions
>     ON answers.question_id = questions.id
>   INNER JOIN sub_categories
>     ON questions.sub_category_id = sub_categories.id
>   INNER JOIN (SELECT RAND() as random_number) as sqy
> WHERE
>   sub_categories.category_id = 1
> AND
>   questions.id > random_number;