强制执行独特的列

发布于 2024-11-18 15:13:17 字数 73 浏览 7 评论 0原文

如果数据库表结构中的列被设置为唯一,是否需要通过脚本检查表中是否已存在要插入的新值?或者只插入值让 DBMS 过滤非新值就可以了吗?

If a column is made unique in a database table structure, is there any need to do a check to see if a new value to be inserted already exists in the table via script? Or would it be fine just to insert values letting the DBMS filter non-new values?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

娜些时光,永不杰束 2024-11-25 15:13:17

当您尝试在唯一列中插入重复值时,插入查询将失败。因此,确保检查插入查询是否顺利可能是个好主意。尽管无论情况如何,您都应该始终检查插入查询是否完成:)

When you will try to insert a duplicate value in a unique column, your insert query will fail. So it might be a good idea to make sure you are checking to see if your insert queries went well or not. Althought regardless of the situation you should always check if your insert query went through or not :)

初懵 2024-11-25 15:13:17

在将数据插入数据库之前,您应该始终验证数据。话虽这么说,如果您尝试在唯一定义的列上插入非唯一值,将会发生 SQL 异常。

为了在插入之前验证这一点,您可以执行以下操作:

 select 1
 from mytable_with_unique_column
 where my_unique_column = myNewValue

如果查询返回任何内容,则不要尝试插入,因为这会引发 SQLException。

You should always validate your data before inserting it on the database. That being said, what will happen if you try to insert a non-unique value on a unique defined column is an SQLexception.

In order to validate this before insertion, you could for example do a

 select 1
 from mytable_with_unique_column
 where my_unique_column = myNewValue

If the query returns anything, then simply do not try to insert as that will throw an SQLException.

池予 2024-11-25 15:13:17

验证唯一约束绝对是一种矫枉过正。

当您对列施加唯一约束时,会为此列创建隐式索引。因此,DBMS 可以(并且将会)更快地验证您的数据。不幸的是,当您尝试将重复值插入到列中时,您将遇到必须处理的约束冲突异常(但在使用脚本验证时也必须处理此类错误)。

祝你好运。

Verification of unique constraint is definitely an overkill.

When you put unique constraint on your column, an implicit index is created for this column. Thus, DBMS can (and will) verify your data much faster. Unfortunately, when you try to insert duplicate value into your column, you will get constraint violation exception you have to deal with (but you have to deal with such error while using script verification either).

Good luck.

谷夏 2024-11-25 15:13:17

您可以将插入语句和验证选择合并到一个语句中:

insert into mytable_with_unique_column (...) values (...)
where not exists
(
  select 1
  from mytable_with_unique_column
  where my_unique_column = myNewValue
)

如果尚不存在具有给定唯一值的行,则只会插入新行。

You can combine the insert statement and validation select into one statement:

insert into mytable_with_unique_column (...) values (...)
where not exists
(
  select 1
  from mytable_with_unique_column
  where my_unique_column = myNewValue
)

This will only insert a new row if there isn't already a row with the given unique value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文