带有选择性标准的 TSQL 随机选择
- 作者: 您的用户名未注册
- 来源: 51数据库
- 2022-12-01
问题描述
我的数据库在category"表中有 5 个类别.我还有一个名为items"的表,其中每个项目都有唯一的 Id 和一个类别 Id FK.
My database has 5 categories in table "category". I also have a table called "items", where each item has unique Id and a category Id FK.
我需要从 1 个类别中随机选择 10 个项目.
I need to randomly select 10 items from 1 category.
如果只有 1 个类别,这不会有问题.但是表items"以非顺序存储类别id.
This would not be problem if there was only 1 category. But table "items" stores categories id in non-sequential order.
下面的随机选择语句有效并且能够在一个范围内生成随机 ID.但是如何生成 10 个属于同一类别的随机 ID?
The random select statement below works and is able to generate random IDs within a range. But how can I generate 10 random IDs that belong to the same category?
Declare @maxRandomValue tinyint = 100
, @minRandomValue tinyint = 0;
Select Cast(((@maxRandomValue + 1) - @minRandomValue)
* Rand() + @minRandomValue As tinyint) As 'randomNumber';
定义:
Table Categories ID INT Desc Varchar(100) Table Items ID Int CategoryID Int (fk) Desc Varchar(100)
推荐答案
使用
- 过滤类别的 WHERE
- 新增随机行
- TOP 限制您最多 10 个项目
所以:
SELECT TOP 10 * FROM Items WHERE CategoryID = @whatever ORDER BY NEWID()
推荐阅读
热点文章
检查拆分键盘
0
带有“上一个"的工具栏和“下一个"用于键盘输入AccessoryView
0
Activity 启动时显示软键盘
0
UIWebView 键盘 - 摆脱“上一个/下一个/完成"酒吧
0
在 iOS7 中边缘滑动时,使键盘与 UIView 同步动画
0
我的 iOS 应用程序中的键盘在 iPhone 6 上太高了.如何在 XCode 中调整键盘的分辨率?
0
android:inputType="textEmailAddress";- '@' 键和 '.com' 键?
0
禁用 iPhone 中键盘的方向
0
Android 2.3 模拟器上的印地语键盘问题
0
keyDown 没有被调用
0
