sql – 基于密钥的随机SELECT查询

是否可以基于密钥随机化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

最佳答案 您可以使用
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));
点赞