0

我有 2 张桌子。在table_1我有每天更新的不同任务。在table_2我有工人名单。我需要自动随机地将 1 个工作人员(table_2)分配给 1 个任务(table_1),这样每个工作人员将拥有大致相同数量的任务。

我尝试使用rand()方法,它随机分配但不均等,我的意思是一名工人可以比另一名工人有更多的任务要做。然后我尝试使用count()方法,但无法连接它们......我是 php 和 mysql 的新手 :(

我做了这样的东西,但只在 mysql 中,但由于(不是)功能,它只能工作一次。

insert into table_1(worker) 
    select col_1 from table_2 
    where col_1 not in (select worker from table_1) 
    order by col_1 rand() 
    limit 0,1;

谢谢你的帮助 :)

4

2 回答 2

0

为了随机分配任务,我首先将任务随机化,然后通过简单地遍历工作人员数组列表并在执行过程中一个接一个地将任务附加到它们上,将它们分发给工作人员。这是我的意思的一个想法。显然我没有你的代码的全部细节,但我希望它有所帮助。

// assuming you already have a list of tasks and workers fetched from the database
// and flattened into simple integer indexed arrays. I'll call them $workers 
// and $tasks

// create an array of tasks per worker
$worker_tasks = array();

// randomize the tasks
shuffle($tasks); // built in php function
while(!empty($tasks)){
    foreach($workers as $worker){
        if(empty($tasks)) break;

        // add a new task under the worker
        $worker_tasks[$worker][] = array_pop($tasks);
    }
}

// insert the array of worker_tasks into w/e table you want.
// high five everyone
于 2012-05-18T13:15:32.150 回答
0

我有2个解决方案给你。第一个更简单,但前提是您可以修改 table_2 以添加当前分配的任务数的字段。这将是一个计数器,您将初始化为 0,然后在每次分配任务时递增。如果您可以修改您的表,这将选择分配最少任务的工作人员:

select worker_id, MIN(tasks_assigned)
FROM table_2
GROUP BY worker_id

这是一个循环分配器,但并不是那么随机。我认为公平分配更重要。如果您无法更改表格,则相同的解决方案会更加混乱:

CREATE TEMPORARY TABLE task_list
( worker_id INT,
  tasks_assigned INT )

SELECT INTO task_list
  SELECT worker_id, count(worker_id) AS tasks_assigned
  FROM table_1
  GROUP BY worker_id

SELECT INTO task_list
  SELECT worker_id, 0 
  FROM table_2
  WHERE worker_id NOT IN (SELECT worker_id FROM task_list)

SELECT worker_id MIN(tasks_assigned) 
FROM task_list
GROUP BY worker_id  

Obviously this isn't the entire solution. But this will give you a worker_id that has the fewest number of tasks assigned. You'll then have to use this id to do an update to your task table (table_1)

于 2012-05-18T13:26:54.947 回答