我有2张桌子
获得随机产品并将其插入其他表的第一部分当然很容易。但是我不知道如何将这些产品分配给不同的用户(4个用户,每个用户都需要3个产品)。所以我的方法是按照以下步骤使用临时表:
DROP PROCEDURE IF EXISTS get_verify;
DELIMITER //
CREATE PROCEDURE get_verify()
BEGIN
-- trunc the temp table
TRUNCATE TABLE temp_tbl;
-- reset auto_increment
ALTER TABLE temp_tbl AUTO_INCREMENT = 1;
-- insert random producst into temp table
insert into temp_tbl (`prod_id` ,`closed_on` ,`closed_by`)
SELECT prod_num as prod_id, DATE_FORMAT (closed,'%d.%m.%Y' )as closed_on ,agent as closed_by
FROM tbl_products a
WHERE DATE(closed) > (NOW() - INTERVAL 7 DAY)
ORDER BY RAND()
LIMIT 12;
-- update temp table and assign products to the users
update temp_tbl
set verify_by =
case
when id in (1,2,3) then 1
when id in (4,5,6) then 2
when id in (7,8,9) then 3
when id in (10,11,12) then 4
else 0
end
;
-- insert data from temp table to final table
insert into tbl_verify (`prod_id` ,`closed_on` ,`closed_by` , verify_by)
select prod_id, closed_on, closed_by, verify_by
from temp_tbl
;
commit;
END //
DELIMITER ;
解释我的工作
一切正常,只是想检查是否有更好的方法。
谢谢
答案 0 :(得分:1)
您的ALTER TABLE temp_tbl AUTO_INCREMENT = 1;
是多余的,TRUNCATE
已经为您做到了。
您的临时表(以及整个过程)也是多余的。您可以借助user-defined variables在一个语句中完成所有这些操作。
insert into tbl_verify (`prod_id`, `closed_on`, `closed_by`, verify_by)
select prod_id, closed_on, closed_by, user from (
SELECT prod_num as prod_id, DATE_FORMAT(closed,'%d.%m.%Y') as closed_on ,agent as closed_by
, @row := @row + 1 as row
, case when @row between 1 and 3 then 1
when @row between 4 and 6 then 2
when @row between 7 and 9 then 3
when @row between 10 and 12 then 4
else 0 end as user
FROM tbl_products a
, (select @row := 0) v
WHERE DATE(closed) > (NOW() - INTERVAL 7 DAY)
ORDER BY RAND()
LIMIT 12
) sq