gpt4 book ai didi

mysql - MYSQL 5.0.27 如何创建触发器来防止插入重复行?

转载 作者:行者123 更新时间:2023-11-29 01:40:33 25 4
gpt4 key购买 nike

这个问题跟在上一个问题之后。 is it possible to make a field in Mysql table to to have length max=700, to be unicode (3 bytes) and to be unique?

我有一个表 MyText,它有 ID 列、text 列和许多其他列

Id - text           - type ..& other fileds1  - this is my text2  - xxxx

I want the text column support unicode with max length can hold 700 Unicode characters. I can't set Unique (text) because MYSQL only supports 765 bytes max length for unique column while Unicode takes 3 bytes so I need 2100 bytes (700*3) unique column.

So, the solution is to crate a trigger that prevents the user to insert the duplicate. For example, if user inserts "THIS is My Text" (We won't care case sensitive) into MyText table, then Mysql will abort completely ALL Queries that contain that Inserting Statement and will generate an SQLException to prevent the system to do other query.

Ok, suppose you have to run a series of sql statements in your Java code

insert into MyText('THIS is My Text',1);
insert into OtherTable ('some text');
update othetTable...

然后,当系统执行 insert into MyText('THIS is My Text',1); 时,它应该停止执行下面的其他查询。

此外,有些人建议使用 prefix index 来帮助 Nysql 更快地执行 select,但我不确定是否有必要,因为我得到了 ID colum已编入索引。

注意:MYSQL 5.027 是 2006 版本,已经很老了,但我喜欢它

那么如何创建满足我要求的触发器或如何解决我的问题?

最佳答案

出于性能原因,我建议不要为此使用触发器。

相反,创建一个额外的列来存储 MD5SHA1您的值的哈希值,并使用约束使该列唯一。

根据以上链接,两种哈希函数都存在于您的 MySQL 版本中。或者,如果将它集成到您​​的 Java 代码中更容易,您可以使用 MessageDigest 在 Java 中进行哈希处理。类。

问题中您指出如果插入语句由于重复而失败则不应执行进一步查询的部分最好使用 transactions 处理。 .使用普通 JDBC 或大多数 ORM 框架的 Java 也支持这些。

关于mysql - MYSQL 5.0.27 如何创建触发器来防止插入重复行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24986670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com