SQL語句如何實現從資料庫表中查詢隨機資料的記錄

2021-08-29 15:40:07 字數 1132 閱讀 1075

需要從資料庫表中隨機讀取n條記錄,必須保證每條記錄都不相同.

原來的想法是弄兩個鍊錶,第乙個讀取對應資料庫表中的所有記錄,根據每個記錄的id來生成這個鍊錶;第二個鍊錶是有選定的隨機讀取的記錄生成的,這樣從第乙個鍊錶中選定的,就可以剪掉,以後就不會被選種,把選中的新增到第二個鍊錶中.

後來發現,在不同的資料庫中完全可以用sql語句來實現隨機選定不同記錄.

這裡把不同資料庫實現的語句粘在這裡,以供需要的人來參考.

[size=large]select a random row with mysql:[/size]

select column from table   

order by rand()

limit 1

[size=large]select a random row with postgresql: [/size]

select column from table   

order by random()

limit 1

[size=large]select a random row with microsoft sql server: [/size]

select top 1 column from table   

order by newid()

[size=large]select a random row with ibm db2: [/size]

select column, rand() as idx    

from table

order by idx fetch first 1 rows only

[size=large]select a random record with oracle: [/size]

select column from   

( select column from table

order by dbms_random.value )

where rownum = 1

資料庫SQL語句實現

1 建立資料庫 create database if not exists cs2013 2 建立資料庫 create table if not exists comp id int not null primary key auto increment pid varchar 30 not nul...

資料庫表維護(sql語句)

新增字段 alter table 表名 add 欄位名 nvarchar 50 null 刪除字段 alter table 表名 drop column 欄位名 修改字段 alter table 表名 alter column 欄位名 nvarchar 50 null 重新命名表 access 重新...

民族資料庫表SQL語句

create table dbo b nation code char 2 not null primary key nation varchar 20 insert into b nation values 01 漢族 insert into b nation values 02 蒙古族 inse...