根据这篇文章:http://net.tutsplus.com/tutorials/other/top-20-mysql-best-practices/ 使用 ORDER BY RAND() 是个坏主意,因为:
The problem is, MySQL will have to perform RAND() operation (which takes processing power) for every single row in the table before sorting it and giving you just 1 row.
现在一些工作的家伙,最近发现你可以在使用 MsSQL 时使用 ORDER BY NEWID() (我不太了解)。现在,我的问题是,使用 NEWID() 是否和使用 RAND() 一样都是一个坏主意 - 如果是,那么应该如何完成?
最佳答案
这是 MySQL
的 RAND()
调用的代码:
double my_rnd(struct rand_struct *rand_st)
{
rand_st->seed1=(rand_st->seed1*3+rand_st->seed2) % rand_st->max_value;
rand_st->seed2=(rand_st->seed1+rand_st->seed2+33) % rand_st->max_value;
return (((double) rand_st->seed1)/rand_st->max_value_dbl);
}
您可以评估几个间接、添加和模数所需的处理能力。
ORDER BY RAND()
的真正问题是它需要对(可能很大的)随机数组进行排序,而不是计算它们。
当然,同样的问题也适用于 SQL Server
。
在 MySQL
中,您可以避免对随机记录进行排序:
但是,此解决方案不适用于 SQL Server
,因为它不支持 session 变量。
关于mysql - MsSQL NEWID 是否像 MySQL Rand() 一样糟糕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5501489/