Sql server 获取不包括已获取项的项的SQL查询

Sql server 获取不包括已获取项的项的SQL查询,sql-server,linq,Sql Server,Linq,我需要sql查询从表中获取随机项,不包括以前以相同方式获取的项。我尝试以我现在能想到的最佳方式回答您的解决方案。但是仍然有一些我没有考虑的不清楚的问题,例如 当以前选择的值用完时,您会怎么做?那你什么都不还了?因为在某一点上,您随机选择了所有值 它应该选择多少项,“以前”的具体术语是什么 测试数据 CREATE TABLE dbo.randomitems (namesused nvarchar(50)) CREATE TABLE dbo.randomlist (namesused nvarc

我需要sql查询从表中获取随机项,不包括以前以相同方式获取的项。

我尝试以我现在能想到的最佳方式回答您的解决方案。但是仍然有一些我没有考虑的不清楚的问题,例如

  • 当以前选择的值用完时,您会怎么做?那你什么都不还了?因为在某一点上,您随机选择了所有值

  • 它应该选择多少项,“以前”的具体术语是什么

  • 测试数据

    CREATE TABLE dbo.randomitems (namesused nvarchar(50))
    CREATE TABLE dbo.randomlist (namesused nvarchar(50))
    CREATE TABLE dbo.randoms (Names nvarchar(50))
    
    insert into dbo.Randoms (Names) values ('a'), ('u'), ('p'), ('g'),
    ('j'), ('k'), ('l'), ('t')
    
    SQL脚本

    declare @randomitem nvarchar(50)
    declare @firstrun int = (select count(*) from dbo.randomlist)
    
    
    
    if(@firstrun = 0)
    BEGIN
    SELECT top 1 @randomitem=[Names]
      FROM   [LegOgSpass].[dbo].[Randoms]
      
      order by newid();
     
    truncate table dbo.randomitems;
    insert into dbo.randomitems
    select @randomitem
    ;
    
    select * from dbo.randomitems a
    where not exists (select * from dbo.randomlist b where a.namesused = b.namesused);
    
    insert into dbo.randomlist
    select @randomitem;
    END
    
    if(@firstrun >= 1)
    BEGIN
    SELECT top 1 @randomitem=[Names]
      FROM   [LegOgSpass].[dbo].[Randoms]  a
      where not exists (select * from dbo.randomlist b where a.Names = b.namesused)
      
      order by newid();
    
    
    truncate table dbo.randomitems;
    insert into dbo.randomitems
    select @randomitem
    ;
    
    select * from dbo.randomitems a
    where not exists (select * from dbo.randomlist b where a.namesused = b.namesused);
    
    insert into dbo.randomlist
    select @randomitem;
    END
    
    选择

    select * from  dbo.Randoms
    select * from  dbo.randomitems
    select * from  dbo.randomlist
    

    您是要将所有这些都作为一个查询来执行,还是将元素列表重新提供给一个辅助查询?@Gerik我希望在同一个查询中使用它。您真的需要提供更多信息吗?你是不是每次都想要一个随机的?您想随机选择这一个,不包括您之前显示的内容吗?