萬盛學電腦網

 萬盛學電腦網 >> 數據庫 >> mysql教程 >> mysql如何隨機抽取數據庫裡的幾條數據

mysql如何隨機抽取數據庫裡的幾條數據

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 秒

copyright © 萬盛學電腦網 all rights reserved