如何在MySQL随机选择记录
The easiest way to generate random rows in MySQL is to use the ORDER BY RAND() clause.
SELECT col1 FROM tbl ORDER BY RAND LIMIT 10;
This can work fine for small tables. However, for big table, it will have a serious performance problem as in order to generate the list of random rows, MySQL need to assign random number to each row and then sort them.
Even if you want only 10 random rows from a set of 100k rows, MySQL need to sort all the 100k rows and then, extract only 10 of them.
My solution for this problem, is to use RAND in the WHERE clause and not in the ORDER BY clause. First, you need to calculate the fragment of your desired result set rows number from the total rows in your table. Second, use this fragment in the WHERE clause and ask only for RAND numbers that smallest (or equal) from this fragment.
For example, suppose you have a table with 200K rows and you need only 100 random rows from the table. The fragment of the result set from the total rows is: 100 / 200k = 0.0005.
The query will look like:
SELECT col1 FROM tbl WHERE RAND()<=0.0005;
In order to get exactly 100 row in the result set, we can increase the fragment number a bit and limit the query:
For example:
SELECT col1 FROM tbl WHERE RAND()<=0.0006 limit 100;
- MySQL如何选择随机记录?
- mysql 随机选择一条记录
- 如何随机的从mysql表中取出一条记录?
- 如何随机取记录?(MSSQL、Access、MySql)
- 如何随机的从mysql表中取出一条记录?
- mysql 如何选择随机行
- mysql 如何选择随机行
- mysql中随机选择记录的方法
- 随机选择记录(mysql)
- MySQL中如何实现Top N及M至N段的记录查询?
- 随机获取Mysql数据表的一条或多条记录
- 如何在无穷的数据流随机选择m个数
- MYSQL中随机读取数据库表中的记录-ORDER BY rand()
- 33. 百度面试题:有一个很大很大的输入流,大到没有存储器可以将其存储下来,而且只输入一次,如何从这个输入 流中随机取得m个记录
- Oracle随机选择一条记录SQL
- mysql使用rand随机查询记录效率测试
- mysql学习七之mysql的存储引擎,存储引擎的区别,如何选择存储引擎。
- (转)如何在MySql中记录SQL日志(例如Sql Server Profiler)
- mysql 分组查询数据时,如何获得用于分页的总记录数?
- mysql如何删除重复记录