我运行以下MySQL代码来创建full_contact_social_networks表
CREATE TABLE `full_contact_social_networks` (
`id` bigint(20) UNSIGNED NOT NULL,
`base_id` bigint(20) UNSIGNED NOT NULL,
`name` varchar(24) COLLATE utf8_unicode_ci DEFAULT NULL,
`slug` varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
ALTER TABLE `full_contact_social_networks`
ADD PRIMARY KEY (`id`),
ADD KEY `base_id` (`base_id`);
ALTER TABLE `full_contact_social_networks`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT;
然后我想创建一个触发器,将slug列的值设置为base_id + name的sha256。我使用以下内容:
CREATE TRIGGER full_contact_social_networksUpd BEFORE UPDATE ON full_contact_social_networks
FOR EACH ROW SET `slug` = SHA2((CONCAT (`base_id`, `name`)), 256);
但是这给了我以下错误消息:
[errno] => 1193
[sqlstate] => HY000
[error] => Unknown system variable 'slug'
答案 0 :(得分:1)
在触发器主体中,OLD和NEW关键字使您可以访问 受触发器影响的行中的列。旧的和新的是MySQL 触发器的扩展;它们不区分大小写。
参考:http://dev.mysql.com/doc/refman/5.7/en/trigger-syntax.html
所以你的触发器必须是:
CREATE TRIGGER full_contact_social_networksUpd BEFORE UPDATE ON full_contact_social_networks
FOR EACH ROW SET NEW.slug = SHA2((CONCAT (NEW.base_id, NEW.name)), 256);
但这仅适用于更新,您可能也需要一个用于插入。在mysql中你不能有一个触发器,说INSERT OR UPDATE你需要两个触发器
CREATE TRIGGER full_contact_social_networksIns BEFORE INSERT ...