基于密钥的随机SELECT查询

时间:2015-05-21 09:39:42

标签: sql sql-server tsql

是否可以根据键随机化SELECT?

我使用此查询来随机查询:

SELECT * FROM tbl_news ORDER BY NEWID();

是否有基于的随机查询功能或类似方法:

SELECT * FROM tbl_news ORDER BY NEWID(15);

5,1,3,2,4

使用相同的键:

SELECT * FROM tbl_news ORDER BY NEWID(15);

5,1,3,2,4

使用另一个键:

SELECT * FROM tbl_news ORDER BY NEWID(36);

2,5,1,3,4

2 个答案:

答案 0 :(得分:2)

你可以使用HASHBYTES,虽然它可能不会在大量行上表现出色(尽管NEWID()也没有),例如。

-- CREATE SAMPLE DATA
IF OBJECT_ID(N'tempdb..#tbl_news', 'U') IS NOT NULL DROP TABLE #tbl_news;
CREATE TABLE #tbl_news (NewsID INT IDENTITY);
INSERT #tbl_news DEFAULT VALUES;
INSERT #tbl_news DEFAULT VALUES;
INSERT #tbl_news DEFAULT VALUES;
INSERT #tbl_news DEFAULT VALUES;
INSERT #tbl_news DEFAULT VALUES;

-- DEFINE YOUR SORT KEY
DECLARE @Key INT = 15;

SELECT  *
FROM    #tbl_news
ORDER BY HASHBYTES('MD5', CONVERT(VARCHAR(10), NewsID + @Key));

-- SAME ORDER AS FIRST SELECT TO SHOW SORT IS REPEATABLE
SELECT  *
FROM    #tbl_news
ORDER BY HASHBYTES('MD5', CONVERT(VARCHAR(10), NewsID + @Key));


SET @Key = 36;

-- WITH A NEW KEY SHOW DIFFERENT ORDER
SELECT  *
FROM    #tbl_news
ORDER BY HASHBYTES('MD5', CONVERT(VARCHAR(10), NewsID + @Key));

-- BUT NEW ORDER IS STILL REPEATABLE
SELECT  *
FROM    #tbl_news
ORDER BY HASHBYTES('MD5', CONVERT(VARCHAR(10), NewsID + @Key));

答案 1 :(得分:0)

你想要的是随机种子。见here。种子使随机数可重复。我认为解决方案是使用种子并将它们放入表中,然后将此表与您的表连接以找到所需的列表。请参阅下面的示例。

DECLARE @SEED INT = 100;
DECLARE @SIZE INT = 5;
-- url http://www.codeproject.com/Tips/811913/Generating-a-set-of-random-numbers-in-SQL-Server
WITH RandomNumbers (RowNumber, RandomNumber) AS (
    -- Anchor member definition
    SELECT  1                         AS RowNumber, 
            RAND(@SEED) AS RandomNumber
    UNION ALL
    -- Recursive member definition
    SELECT  rn.RowNumber + 1          AS RowNumber, 
            RAND( 1000000000* RAND(@SEED + rn.RowNumber))  AS RandomNumber
    FROM RandomNumbers rn
    WHERE rn.RowNumber < @SIZE
)
-- Statement that executes the CTE
SELECT  rn.RowNumber, rn.RandomNumber
FROM RandomNumbers rn
INNER JOIN tbl_news n
ON rn.RowNumber = n.ID
ORDER BY rn.RandomNumber