如何在 MySQL 中循环触发器


BEGIN
DECLARE offset_val int ;
declare count_val int ;
SET @count_val  = ((SELECT COUNT(users.sk_user_id) FROM users); 
SET @offset_val =1;
WHILE offset_val <= count_val DO
SET @userId  = (SELECT users.sk_user_id FROM users LIMIT 1 OFFSET  offset_val) ; 
INSERT INTO `user_notification` (`sk_user_nofication_id`, `user_notification_text`, 
`user_notification_gif`, `general_notification_id`, `user_id`, `type`, `status`, `time_stamp`)
VALUES (NULL, 'hf', new.general_notification_text, 
new.sk_general_nofication_id, @userId, 'general', 'unread', CURRENT_TIMESTAMP);
SET offset_val = offset_val + 1 ;
END WHILE ;
END

使用 SQL 时,应该考虑集合中的数据,而不是一次考虑一行。

例如,在这种情况下,您根本不需要循环。您可以在一个操作中复制所需的所有行:

BEGIN
INSERT INTO `user_notification` (`sk_user_nofication_id`, `user_notification_text`, 
`user_notification_gif`, `general_notification_id`, `user_id`, `type`, `status`, `time_stamp`)
SELECT NULL, 'hf', NEW.general_notification_text, 
NEW.sk_general_nofication_id, sk_user_id, 'general', 'unread', CURRENT_TIMESTAMP()
FROM users;
END

这会在user_notification中插入与SELECT返回的行数一样多的行数。

选择列表中的某些列来自users表,某些列是可以在触发器中引用的NEW.*列的一部分,还有一些是常量值。

这是使用INSERT向表中添加一组行的常用方法。

最新更新