且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

好主意/坏主意?在一小组子查询结果之外使用MySQL RAND()?

更新时间:2023-11-27 17:06:10

实际上...我最终进行了测试,并且我可能已经回答了自己的问题.我以为我会在此处发布此信息,以防对其他人有用. (如果我在这里做错了什么,请告诉我!)

Actually...I ended up running a test and I might have answered my own question. I thought I'd post this information here in case it was useful for anyone else. (If I've done anything wrong here, please let me know!)

这真是令人惊讶...

This is kind of surprising...

与已阅读的所有内容相反,我创建了一个名为TestData的表,该表具有100万行,并运行以下查询:

Contrary to everything that I've read, I created a table called TestData with 1 million rows and ran the following query:

SELECT * FROM TestData WHERE号= 41 ORDER BY RAND()限制8

SELECT * FROM TestData WHERE number = 41 ORDER BY RAND() LIMIT 8

...,它平均返回0.0070秒的行.我真的不明白为什么RAND()的声誉如此差.至少在这种情况下,对我来说似乎很有用.

...and it returned the rows in an average of 0.0070 seconds. I don't really see why RAND() has such a bad reputation. It seems pretty usable to me, at least in this particular situation.

我的表格中有三列:

id [BIGINT(20)] |文本字段[tinytext] |编号[BIGINT(20)]

id [BIGINT(20)] | textfield [tinytext] | number [BIGINT(20)]

ID上的主键,数字上的索引.

Primary Key on id, index on number.

我认为MySQL足够聪明,可以知道它只应将RAND()应用于"WHERE number = 41"返回的20行? (我只添加了20行,其数字"的值为41.)

I guess MySQL is smart enough to know that it should only be applying RAND() to the 20 rows that are returned by "WHERE number = 41" ? (I specifically added only 20 rows that had the value 41 for 'number'.)

备用子查询方法返回结果的平均时间约为.0080秒,这比非子查询方法要慢.

The alternate subquery method returns results with an average time of around .0080 seconds, which is slower than the non-subquery method.

子查询方法:SELECT * FROM(SELECT * FROM TestData WHERE number = 41)as t ORDER BY RAND()LIMIT 8

Subquery method: SELECT * FROM (SELECT * FROM TestData WHERE number = 41) as t ORDER BY RAND() LIMIT 8