gpt4 book ai didi

Mysql按rand排序并设置用户变量

转载 作者:行者123 更新时间:2023-11-29 04:13:00 25 4
gpt4 key购买 nike

谁能解释一下下面的 SQL 发生了什么?我知道 order by rand 不是一个好的做法,但我有兴趣解释为什么会发生这种情况

create database test_views_rand;
use test_views_rand;
create table test_table (number int);

insert into test_table values (1), (2), (3), (4);

select @test := number from test_table order by rand() limit 1;
# selects a random number from 1 - 4
select @test;
# Always gives 4, regardless of what the actual number was in the select query

以防万一,第一个选择语句如预期的那样是随机的。无论第一个 select 语句的结果如何,第二个 select 语句总是给出 4。

最佳答案

如@bw_üezi 所说,作业是在订购之前完成的。

select @test := number, @aa:=(@a:=@a+1), @a, @r 
from test_table, (select @a:=0) a
order by (@r:=rand());

结果

|| 3 || 3 || 3 || 0.160410950109745  ||
|| 4 || 4 || 4 || 0.0159870376959322 ||
|| 1 || 1 || 1 || 0.161011773311544 ||
|| 2 || 2 || 2 || 0.928689247862146 ||

然后选择@test,@aa,@a,@r结果

|| 2 || 2 || 4 || 0.015987037695932  ||

如果 @aa 最后只有 2,怎么会是 4?

这是因为错误修正:http://bugs.mysql.com/bug.php?id=16861

updates variable from the result_field value when being sent to a client.

在选择部分不属于表达式的用户变量赋值被执行两次(至少在最后一行,其他的不确定)

在查询中操作用户变量通常会产生意想不到的结果。

你最好使用查询:

select @test := (select number from test_table order by rand() limit 1);

set @test := (select number from test_table order by rand() limit 1); 

关于Mysql按rand排序并设置用户变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5384346/

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