SQL Server随机读取一个表中若干条记录:
示例:
代码如下 | 复制代码 |
select top 10 id,title from news order by newid() |
优化之后
在MSSQL中用以下方法随机读取3W多条数据,只用了1-2秒。而在实际运用中,肯定是不会随机读取这么多数据的
MSSQL
代码如下 | 复制代码 |
select id from tablename where id >= (select floor(rand() * ((select max(id) from tablename) - (select min(id) from tablename)) + (select min(id) from tablename))) order by id |
mySql 随机读取数据
rand()函数
代码如下 | 复制代码 |
select * from users order by rand() LIMIT 1 |
这条语随机取一条记录还是不错的选择
代码如下 | 复制代码 |
SELECT * FROM users AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(userId) FROM `users`)-(SELECT MIN (userId) FROM users))+(SELECT MIN(userId) FROM users)) AS userId) AS t2 WHERE t1.userId >= t2.userId ORDER BY t1.userId LIMIT 1 |
执行该sql语句,用时0.039s,效率太给力了
代码如下 | 复制代码 |
SELECT * FROM users WHERE userId >= ((SELECT MAX(userId) FROM users)-(SELECT MIN(userId) FROM users)) * RAND() + (SELECT MIN(userId) FROM users) LIMIT 1 |