2013-10-31 21 views
0

我有三個表:插入到SQL表使用隨機和常量值

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

每個表的標識作爲主鍵,在EventAllocations的peopleid和事件ID是外鍵。

基本上,我想隨機分配人員到一個特定的事件(考慮陪審團選擇或隨機票獎勵)。

我想創建一個查詢:

  1. 隨機地從人民表20行,在新行中EventAllocations寫的peopleid
  2. 在每個這些新創建的寫入的事件ID恆定值行

我已經設法通過使用兩個單獨的查詢來達到預期的效果。

查詢之一:

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)); 

NB我使用Access 2007年。

這一切似乎太沒效率了 - 是在那裏會對此有更好的方式?理想情況下,我希望一個查詢同時完成兩項任務。

回答

0

你的意思是這樣的嗎?請注意,您必須在內部聯接後添加任何邏輯,因爲它現在只選擇第一個正在刪除的標識符。它爲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