隨機取mysql的N條資料

2021-06-15 00:48:59 字數 1060 閱讀 8409

先來個看似複雜的:

需要查user表裡,code為100,的隨機不重複的2兩個name值

select * from (select id,name,code from `user` where code='100')

as t1 join (

select round(rand() * ((select max(id) from `user`)-(select min(id) from `user`))+(select min(id) from `user`)) as id

) as t2

where t1.id >= t2.id

order by rand()*(t1.id) limit 2;

以下內容**:

有個需求是這樣:

要先隨機向資料庫裡分別取100條資料,

select * from test order by rand() limit 4 ;

select * from test where id not in (1,2,5) order by rand() limit 4 ;

select * from `user` where id >= (select floor(rand() * (select max(id) from `user`)))  order by rand() limit 2 ;

select * from `user` where id >= (select floor(rand() * (select max(id) from `user`))) and id not in(2,5) order by rand() limit 2 ;

可不可以再快點:

select *

from `user` as t1 join (select round(rand() * ((select max(id) from `user`)-(select min(id) from `busstopinfo`))+(select min(id) from `user`)) as id) as t2

where t1.id >= t2.id

order by t1.id limit 2;

mysql隨機查詢n條資料

遇到乙個業務需求是隨機查詢n條資料,一開始使用這種寫法 select from table order by rand limit n後來發現這種寫法的查詢效率極低,並且官方也不推薦使用。又經過查詢發現網上很多教程更靠譜的寫法如下 select from table as t1 join selec...

mysql 取每個分類的前N條資料。

現有乙個這樣的需求 在一張表中取有100個分類下的1000條資料。現要取每個分類下的前4條資料。表結構如下 id varchar 32 not null comment id isvalid varchar 2 default null comment 邏輯刪除標識1正常0刪除 createtime...

Oracle 隨機獲取N條資料

oracle 隨機獲取n條資料 當我們獲取資料時,可能會有這樣的需求,即每次從表中獲取資料時,是隨機獲取一定的記錄,而不是每次都獲取一樣的資料,這時我們可以採取oracle內部一些函式,來達到這樣的目的.1 select from select from tablename order by sys...