数据库中随机查询若干条数据

1、MySQL

-- 第一种方法:
SELECT * FROM table_name ORDER BY RAND() LIMIT N;-- 随机查询N条数据

-- 第二种方法:
SELECT * FROM table_name WHERE id >= (SELECT floor(RAND() * (SELECT MAX(id) FROM table_name))) ORDER BY id LIMIT 1; 

-- 第三种方法:
SELECT * FROM table_name AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM table_name)-(SELECT MIN(id) FROM table_name))+(SELECT MIN(id) FROM table_name)) AS id) AS t2 WHERE t1.id >= t2.id ORDER BY t1.id LIMIT 1;

RAND()函数:返回0和1之间产生一个随机浮点数
FLOOR()函数:返回小于等于该值的最大整数

2、SQL Server

select top N column_name from table_name order by NEWID();

NEWID()函数:创建一个全球唯一的标识,该标识是由网卡号、CPU时钟组成,返回值类型为uniqueidentifier类型

-- 插入随机码
insert table_name SELECT NEWID(),column_name  FROM other_name;

你可能感兴趣的:(数据库,sql)