如何在应用ORDER BY NEWID()随机获取时防止重复记录?

时间:2014-02-24 19:46:00

标签: sql sql-server select sql-order-by newid

我尝试使用Return rows in random order中提供的解决方案来获取查询中的随机记录。但我必须将NEWID()添加到我要提取的列列表中,否则我将无法添加ORDER BY NEWID()。不幸的是,它使我的结果集包含重复的记录。

为了进一步说明,由于请求列中存在NEWID(),此查询使我的结果重复:

SELECT distinct top 4 
              Books.BookID,
              Books.Authors,                  
              Books.ShortTitle,               
              NEWID()                 
  FROM Books 
  inner join Publishers on Books.PublisherID = Publishers.PublisherID

  ORDER BY NEWID()

如何克服这个不提取唯一记录的问题(这里的BookID是PK)?

2 个答案:

答案 0 :(得分:4)

你绝对想要为每一行添加newid()。这将取消distinct。相反,将group byorder by newid()`:

一起使用
  SELECT top 4 b.BookID, b.Authors, b.ShortTitle              
  FROM Books b inner join
       Publishers p
       on b.PublisherID = p.PublisherID
  GROUP BY b.BookId, b.Authors, B.ShortTitle
  ORDER BY NEWID();

它会正常工作。您可以按select列表中没有的值排序。

答案 1 :(得分:3)

或者,如果您仍想使用NEWID,只需在分配新ID之前创建一个不同的列表:

SELECT a.BookID, a.Authors, a.ShortTitle FROM
(SELECT distinct top 4 
          Books.BookID AS BookID,
          Books.Authors AS Authors,                  
          Books.ShortTitle AS ShortTitle,                              
FROM Books 
inner join Publishers on Books.PublisherID = Publishers.PublisherID) a
ORDER BY NEWID()