【问题标题】:Inserting into sql table using random and constant values使用随机和常量值插入 sql 表
【发布时间】:2013-10-31 19:47:15
【问题描述】:

我有三张桌子:

People (PeopleID, Name, DOB, Gender etc...)
Events (EventID, EventTitle)
EventAllocations (AllocationID, PeopleID, EventID)

每个表的 ID 用作主键,在 EventAllocations 中 PeopleID 和 EventID 是外键。

基本上,我想将人员随机分配到特定事件(考虑陪审团选择或随机票奖)。

我想创建一个查询:

  1. 从 People 表中随机选择 20 行并将 PeopleID 写入 EventAllocations 的新行中
  2. 在每个新创建的行中写入 EventID 的常量值

我已经设法通过使用两个单独的查询来达到预期的效果。

查询一:

INSERT INTO EventAllocations (PeopleID)
SELECT TOP 20 People.[People ID]
FROM People
ORDER BY Rnd(People.[People ID]);

查询二:

UPDATE EventAllocations SET EventAllocations.EventID = 250
WHERE (((EventAllocations.EventID) Is Null));

注意,我使用的是 Access 2007。

这一切似乎都非常低效 - 有没有更好的方法来解决这个问题?理想情况下,我想要一个同时完成两项任务的查询。

【问题讨论】:

    标签: sql ms-access ms-access-2007


    【解决方案1】:

    你的意思是这样的吗?请注意,您必须在内部联接中添加您所追求的任何逻辑,因为它现在只选择第一个降序 eventid。它是为 MSSQL 编写的,但应该类似。希望对你有帮助

    INSERT INTO EventAllocations (peopleid, eventid)
    SELECT TOP 20 peopleid, x.eventid
    FROM People p
    inner join (select top 1 eventid 
                from events 
                order by eventid desc) x on 1=1
    ORDER BY NEWID(); --Replace NEWID() with your rnd order
    

    【讨论】:

      猜你喜欢
      • 2010-11-30
      • 2016-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-15
      相关资源
      最近更新 更多