我在尝试创建存储过程时遇到了一些问题。我有2个表,eTasks
和eStaff
。以下是每个表的列:
eTasks
TaskID | StaffID | Title | CreateDate
eStaff
StaffID | Name
目前,正如数据所示,所有任务都分配给StaffID'1'。 eTasks
和eStaff
表都使用新任务和工作人员更新,或者它们被取出,这些表每天都不会有相同的行。有些日子,eTask
表中会有1000行,而下一行可能只有400行。有些日子,eStaff
表中会有3名工作人员,下一天可能会有12名。< / p>
我想要做的是在运行存储过程时在当前StaffID
之间均匀分配任务。
到目前为止,这就是我所拥有的:
CREATE PROCEDURE UpdatingeTasksTable
AS
DECLARE t_rowCount INTEGER
DECLARE s_staffIDCount INTEGER
SET t_rowCount = SELECT COUNT(*) FROM eTasks
SET s_staffIDCount = SELECT DISTINCT StaffID FROM eStaff
UPDATE eTasks
SET StaffID = CASE
WHEN TaskID % t_rowCount = 1 THEN 1
WHEN TaskID % t_rowCount = 2 THEN 4
WHEN TaskID % t_rowCount = 3 THEN 3
WHEN TaskID % t_rowCount = 4 THEN 2
END
FROM eTasks b
WHERE TaskID = b.TaskID;
我知道,我的查询目前是什么,它只会将任务分成4个人。有没有办法使CASE语句动态化,这样就不会有一组静态数字?
答案 0 :(得分:0)
这在MySQL中有点困难。您可以通过添加行号列来编写查询来执行此操作:
select et.*, s.staffId
from (select count(*) as cnt
from staff
) ss cross join
(select et.*, (@rne := @rne + 1) as rn
from etasks et cross join
(select @rne := 0) params
) et join
(select s.*, (@rns := @rns + 1) as rn
from staff s cross join
(select @rns := 0) params
) s
on s.rn = mod(et.rn, ss.cnt) + 1;
然后,您可以使用update
:
join
update etask et join
(select et.*, s.staffId
from (select count(*) as cnt
from staff
) ss cross join
(select et.*, (@rne := @rne + 1) as rn
from etasks et cross join
(select @rne := 0) params
) et join
(select s.*, (@rns := @rns + 1) as rn
from staff s cross join
(select @rns := 0) params
) s
on s.rn = mod(et.rn, ss.cnt) + 1
) ets
on et.taskid = ets.taskid
set et.staffid = ets.staffid;
答案 1 :(得分:0)
我得到了这个测试。我没有使用存储过程,我只是在MySQL会话中使用用户定义的变量。但是同样的想法也适用于本地存储的proc变量。
mysql> select count(*) into @staffcount from estaff; -- in my test this is 4
mysql> set @staffid = 0;
mysql> update etasks set staffid = (@staffid := (@staffid+1)%@staffcount)+1;
mysql> select * from etasks;
+--------+---------+-------+------------+
| taskid | staffid | title | createdate |
+--------+---------+-------+------------+
| 1 | 2 | NULL | NULL |
| 2 | 3 | NULL | NULL |
| 3 | 4 | NULL | NULL |
| 4 | 1 | NULL | NULL |
| 5 | 2 | NULL | NULL |
| 6 | 3 | NULL | NULL |
| 7 | 4 | NULL | NULL |
| 8 | 1 | NULL | NULL |
| 9 | 2 | NULL | NULL |
| 10 | 3 | NULL | NULL |
| 11 | 4 | NULL | NULL |
| 12 | 1 | NULL | NULL |
| 13 | 2 | NULL | NULL |
| 14 | 3 | NULL | NULL |
| 15 | 4 | NULL | NULL |
| 16 | 1 | NULL | NULL |
| 17 | 2 | NULL | NULL |
| 18 | 3 | NULL | NULL |
+--------+---------+-------+------------+
这确实假设您的staffid值从1到estaff中的行数。如果你想将值1到4映射到estaff中的相应行,并分配staffid,那么这是一个解决方案:
mysql> update etasks as t,
(select staffid, @rownum:=@rownum+1 AS rownum
from (select @rownum:=0) AS _init cross join estaff) as s
set t.staffid = s.staffid
where s.rownum = (@staffid := (@staffid+1)%@staffcount)+1;