Home > Database > Mysql Tutorial > mysql获取随机数据的方法_MySQL

mysql获取随机数据的方法_MySQL

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-01 13:25:52
Original
1277 people have browsed it

bitsCN.com

1.order by rand()
数据多了极慢,随机性非常好,适合非常小数据量的情况。

SELECT * FROM table_name AS r1 JOIN (SELECT (ROUND(RAND() * (SELECT ABS(MAX(id)-MIN(id)-$limit) FROM table_name))+(SELECT MIN(id) from table_name)) AS id) AS r2 WHERE r1.id >= r2.id ORDER BY r1.id ASC LIMIT $limit;

速度非常快,但是得到的数据是id连续的,没办法解决。
子查询产生一个随机数。
rand()是0到1的随机数,可以等于0到1。
MAX(id)-MIN(id)还要要减去$limit以免结果数量不够$limit条
因为主表id可能不连续,所以r1.id要>=r2.id
还要注意的是有时候最小id不是从1开始的,可能从一个很大的数开始,所以必须加上M(id)的值
手册相关内容:若要在i ≤ R ≤ j 这个范围得到一个随机整数R ,需要用到表达式 FLOOR(i + RAND() * (j

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
MySQL stops process
From 1970-01-01 08:00:00
0
0
0
Error when installing mysql on linux
From 1970-01-01 08:00:00
0
0
0
phpstudy cannot start mysql?
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template