简体   繁体   中英

Inserting into sql table using random and constant values

I have three tables:

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

The IDs for each table serve as the primary key and in EventAllocations PeopleID and EventID are foreign keys.

Basically, I want to randomly allocate people to a specific event (think along the lines of jury selection or a random ticket award).

I want to create a query that:

  1. Randomly selects 20 rows from the People table and writes the PeopleID in new rows in EventAllocations
  2. Writes a constant value for EventID in each of those newly created rows

I have managed to achieve the desired effect by using two separate queries.

Query one:

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

Query two:

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

NB I am using Access 2007.

This all seems horribly inefficient - is there a better way of going about this? Ideally I would like one query that did the two tasks at once.

Do you mean something like this? Note that you will have to add whatever logic you are after in the inner join as it now just selects the first decending eventid. Its written for MSSQL but it should be similar. Hope it helps

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM