NEWID()和多条件组合筛选

本文介绍了SQL数据库中使用NEWID()进行随机抽取的方法,并探讨了如何结合多个条件进行筛选。通过三种不同策略,展示如何在题库中按指定数量和条件随机抽取题目,适用于考试系统等场景。
摘要由CSDN通过智能技术生成

今天看了一个帖子,讲的是数据库随即抽取,以前没接触过,所以整理了下做个笔记。

newid()是SQL SERVER中的函数,创建 uniqueidentifier 类型的唯一值,主要用于随机抽取:

select top n * from tb oder by newid()

对应的,mysql中用rand(),oracle用sys_guid()。

这个常常用于考试系统的随机出题。

例       从题库随机抽出20道题:

           type:类型1的6道,2的7道,3的7道;

           difficulty:难度1的8道,2的12道;

           distinguish:区分1的13道,2的7道

法一:汤姆克鲁斯 提出

select top 6 * from tb where type=1 and difficulty=1 and distinguish=1 oder by newid()

union all

select top 2 * from tb where type=2 and difficulty=1 and distinguish=1 oder by newid()

union all

select top 5 * from tb where type=2 and difficulty=2 and distinguish=1 oder by newid()

union all

select top 7 * from tb where type=2 and difficulty=2 and distinguish=2 oder by newid()

此法查找速度快,但是是根据自己组合的类型,不是真正的随机。

 

法二:sql2015  提出

create table #tb(

        id int ,

        [type] int,

        [difficurity] int,

        [distinguish] int);

 insert into #tb select

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值