简体   繁体   English

跨两列的唯一值 - 在数据库或应用程序级别?

[英]Unique values across two columns - at database or application level?

I need to make my table only allow unique values across two columns - a compound key.我需要让我的表只允许跨两列的唯一值 - 一个复合键。

Would it be more efficient to do this at database level, or should I not create a compound key and let my application check if a record exists for the two unique values about to be submitted, and if so, do not create the row?在数据库级别执行此操作会更有效,还是我不应该创建复合键并让我的应用程序检查是否存在要提交的两个唯一值的记录,如果存在,不创建行?

Compound UNIQUE or PRIMARY keys pose little or no extra burden on database servers beyond what the keys' data types pose.复合 UNIQUE 或 PRIMARY 键对数据库服务器造成的额外负担很少或没有超出键的数据类型造成的负担。 (Data types like long strings with case-insensitive collation make for relatively expensive unique keys, for example. BIGINTs are cheap.) (例如,具有不区分大小写排序规则的长字符串等数据类型会产生相对昂贵的唯一键。BIGINT 很便宜。)

And, if you use compound unique keys, your dbms will serve as a backstop to your application code.而且,如果您使用复合唯一键,您的 dbms 将作为应用程序代码的后盾。 If there's a duplicate, you probably don't want to say "Exception: 1062 Duplicate" to your users.如果有重复,您可能不想对您的用户说“异常:1062 重复”。 You'd be better off saying "that combination is already taken."你最好说“那个组合已经被采用了”。

In the DBMS, go for it.在 DBMS 中,go 为它。 You need support for this feature set both in your table's unique key and your app to get this right.您需要在表的唯一键您的应用程序中都支持此功能集才能做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM