[英]MSSQL Select Random in Large Data
我有一個表,其中有超過100萬條記錄,我想從該表中選擇隨機行,而不是從所有記錄中選擇-僅從符合特定條件的結果中選擇隨機行。
性能非常重要 ,因此我不能使用按NEWID排序,然后選擇第一項。
表結構是這樣的:
ID BIGINT
Title NVARCHAR(100)
Level INT
Point INT
現在,我編寫了一個查詢,例如:
with
tmp_one as
(
SELECT
R.Id as RID
FROM [User] as U
Inner Join
[Item] as R
On R.UserId = U.Id
WHERE ([R].[Level] BETWEEN @MinLevel AND @MaxLevel)
AND ((ABS((BINARY_CHECKSUM(NEWID(),R.Id,NEWID())))% 10000)/100 ) > @RangeOne
),
tmp_two as
(
Select tmp_one.RID as RID
From tmp_one
Where ((ABS((BINARY_CHECKSUM(NEWID(),RID,NEWID())))% 10000)/100 ) > @RangeTwo
),
tmp_three as
(
Select RID as RID
From tmp_two
Where ((ABS((BINARY_CHECKSUM(NEWID(),NEWID())))% 10000)/100 ) < @RangeThree
)
Select top 10 RID
From tmp_three
我嘗試隨機選擇10個項目,然后選擇其中之一,但是我遇到了一個令人驚訝的問題!!!
有時,輸出按項目級別排序! 而且我不想要它(這不是隨機的)。 我真的不知道結果如何按級別排序。
請提出一些解決方案,這些解決方案可以幫助我選擇高性能的隨機記錄,而在高迭代范圍內選擇隨機記錄則不是重復的。
基於MSDN的從大表中隨機選擇行 ,而不是避免的一種:
select top 10 * from TableName order by newid()
它表明:
select top 10 * from TableName where (abs(cast((binary_checksum(*) * rand()) as int)) % 100) < 10
它只有很小的邏輯讀,卻有更好的性能。
嘗試這樣的事情。 它將從您的表中隨機獲取10行。
這是偽代碼,因此您可能需要修復一些列名以匹配實際表。
DECLARE @Random int
DECLARE @Result table
(ID BIGINT,
Title varchar(100),
Level int,
Point int)
declare @TotalRows int
set @TotalRows = (select COUNT(*) From [User] U inner join [Item] R on R.UserID = U.ID)
while (select COUNT(*) from @Result)<10
begin
set @Random = (select floor(RAND() * @TotalRows+1))
insert into @Result
select T1.ID, T1.Title, T1.Level, T1.Point from
(select top (@Random) * From [User] U inner join [Item] R on R.UserID = U.ID) T1
left outer join (select top (@Random) * From [User] U inner join [Item] R on R.UserID = U.ID) T2 on T2.ID = T1.ID
where T2.ID is null
end
select * from @Result
下面是它的工作原理。
Select a random number. For example 47.
We want to select the 47th row of the table.
Select the top 47 rows, call it T1.
Join it to the top 46 rows called T2.
The row where T2 is null is the 47th row.
Insert that into a temporary table.
Do it until there are 10 rows.
Done.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.