插入前触发生成唯一的 md5 哈希值
我正在尝试创建一个触发器,它将唯一的随机字符串与插入表中的每条记录相关联。
到目前为止,我在插入之前创建了一个触发器,它将生成哈希并将其添加到表中。但是,我想知道应该如何确保这个新哈希对于我的表是唯一的。
到目前为止,我有下面的触发器,但正如你所看到的,唯一部分丢失了......
BEGIN
DECLARE newhash VARCHAR(255);
SELECT MD5(CONCAT(NOW(),RAND())) INTO newhash;
SET NEW.`hash` = newhash;
END
I'm trying to create a trigger that will associate an unique random string to every record inserted in a table.
So far I created a trigger, on before insert, that will generate and add the hash to the table. However, I'm wondering how should I go about ensuring this new hash is unique for my table.
So far I have the trigger below, but as you can see the uniques part is missing...
BEGIN
DECLARE newhash VARCHAR(255);
SELECT MD5(CONCAT(NOW(),RAND())) INTO newhash;
SET NEW.`hash` = newhash;
END
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该列在表定义中应该是唯一的,仅此而已。
无论如何,您确定需要 md5(现在 || rand)吗?通过 now 和 rand 的合理实现,您不太可能会出现重复项,但是如果 now() 没有太多粒度或者随机数不是一个好的随机数,那么您可能会在某些情况下遇到麻烦场景。
对于此类事情,使用现成的方案可能是一个更好的主意,例如使用 UUID(MySQL 似乎支持:http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_uuid )。
The column should be unique in the table definition and that's it.
In any case, are you sure that you want md5(now || rand)? With reasonable implementations of now and rand, it's highly unlikely that you are going to have duplicates, but if now() doesn't have a lot of granularity or the random number is not a good random number, you could run into trouble under certain scenarios.
It might be a better idea to use an off-the-shelf scheme for this kind of things, such as using UUIDs (which MySQL seems to support: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_uuid ).