Sql随机取数据

背景:数据库中存储的数据量很大,要用算法建模,为了验证模型,不可能将全部数据捞起来跑。如果只是使用limit 100这样取出数据库中的记录,那么可能刚好取出了某一类数据。为了更好的验证模型,使用随机的方式,取其中的记录,更好。

MsSql随机取数据 select top 10 * from c_cy_admin order by newid()
Access 随机取数据 select  SELECT top 10 id FROM 表1 order by rnd(id)
mySql 随机取数据 SELECT id FROM gueze order by rand() limit 10

Q. 如何得到随机排序结果?
A. 要得到随机排序的列,或者返回x条随机选择的列,你可以使用随机数。但是RAND函数在一个查询中只能返回一个结果。你可以在NOWID函数返回的列上做ORDER BY。请看示例:

SELECT *
FROM Northwind…Orders
ORDER BY NEWID()

SELECT TOP 10 *
FROM Northwind…Orders
ORDER BY NEWID()

这段话翻译得真是费劲,干脆不管原文,直接意译了。
不过提醒大家注意,这种方法是要对整个表扫描,然后产生一个计算列再排序的,最好不要对大的表作这样的操作,否则会很慢的。

Q. How can I randomly sort query results?

A. To randomly order rows, or to return x number of randomly chosen rows, you can use the RAND function inside the SELECT statement. But the RAND function is resolved only once for the entire query, so every row will get same value. You can use an ORDER BY clause to sort the rows by the result from the NEWID function, as the following code shows:

SELECT *
FROM Northwind…Orders
ORDER BY NEWID()

SELECT TOP 10 *
FROM Northwind…Orders
ORDER BY NEWID()

—SQL Server MVPs

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值