在MySQL中以随机顺序生成整数序列

时间:2019-07-18 10:18:33

标签: mysql

还有其他方法可以在MYSQL中按顺序随机生成sequence_no吗??? 我有一张桌子:验证码

SET @a:= 1;
SELECT @a:=@a+1 as sequence_no,captcha_id, captcha_name
FROM captcha,(SELECT @a:= 0) AS a
ORDER BY RAND()

我的预期输出:

sequence_no | captcha_id | captcha_name 
----------------------------------------
01          | 11         | name1
02          | 06         | name2

我的查询输出:

sequence_no | captcha_id | captcha_name
---------------------------------------- 
11           | 11          | name1
06           | 06          | name2

1 个答案:

答案 0 :(得分:1)

要实现此目的,您首先需要在Derived Table内部执行显式随机排序。然后,使用子查询结果来设置序列号(针对随机排序的行):

SET @a:= 0;
SELECT @a:=@a+1 as sequence_no,
       dt.captcha_id, 
       dt.captcha_name 
FROM (
       SELECT captcha_id, captcha_name 
       FROM captcha 
       ORDER BY RAND()
     ) AS dt