mysql如何随机抽取数据库里的几条数据呢?读取随机数只要使用RAND就可以了,方法非常的简单,下面我来给各位举个例子.
数据库连接这些就不贴代码了,直接粘贴sql语句,代码如下:
- SELECT `title` , `id`
- FROM news
- ORDER BY RAND( )
- LIMIT 0 , 5;
随机从new表里取出5条数据,显示id和标题,代码如下:
- mysql> select username from cdb_members order by rand() limit 0,5;
-
- +-----------+
- | username |
- +-----------+
- | Takeshi |
- | icelong |
- | 狗狗请罪 |
- | 菜头 |
- | weike1130 |
- +-----------+
- 5 rows in set (0.01 sec)
- 1、
- SELECT * FROM `table` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM `table`)-(SELECT MIN(id) FROM `table`))+(SELECT MIN(id) FROM `table`)) AS id) AS t2 WHERE t1.id >= t2.id ORDER BY t1.id LIMIT 1;
- 2、
- SELECT * FROM `table` WHERE id >= (SELECT floor( RAND() * ((SELECT MAX(id) FROM `table`)-(SELECT MIN(id) FROM `table`)) + (SELECT MIN(id) FROM `table`))) ORDER BY id LIMIT 1;
最后在php中对这两个语句进行分别查询10次,后者花费时间 0.147433 秒,前者花费时间 0.015130 秒. |