Skip to content
Advertisement

Randomly Assign Rows in Child Table to Row in Parent Table

Using MySQL, I am trying to randomly assign rows in a child table to point to a row in a parent table, per following:

Parent table: There are 50 WorkGroups (Team Alpha, Team Bravo, etc.), each of which can have a maximum number of WorkEmployees.

Child table: There are 2,000 WorkEmployees (Ann, Bob, Carl, etc.) each of whom needs to be assigned to exactly one WorkGroup at random.

  • Using MySQL Each WorkEmployee needs to be assigned to exactly one WorkGroup
  • Each WorkGroup has a specified maximum number of WorkEmployees it can accommodate
  • There are sufficient slots in the WorkGroups to accommodate all WorkEmployees
  • I cannot used stored procedures

Following are the table structures and the UPDATE script I have developed for this purpose. The script is not working. Any guidance on what I have done wrong would be very much appreciated. Thank you.

Advertisement

Answer

The problem besides, that it tales tome to make sample data, is that you havn’t introduced the random factor and that you can only add 1 workgroup to a emplyoee

So adding a ORDER BY RAND() and a ‘LIMIT 1 does the trick

ID | EmployeeName | WorkGroupFK
:- | :----------- | :----------
1  | emp1         | 2          
2  | emp2         | 2          
3  | emp3         | 3          
4  | emp4         | 3          
5  | emp5         | 1          
6  | emp6         | 3          
7  | emp7         | 2          

db<>fiddle here

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement