如何强制执行包含多个表的唯一性规则?
例如,拥有以下表:
Companies (CompanyID)
Workers (WorkerID, CompanyID)
Users (WorkerID, Username)
定义了正确的关系后,如何强制执行以下断言:用户的用户名在其员工所在的公司中是唯一的?
For example, having the tables:
Companies (CompanyID)
Workers (WorkerID, CompanyID)
Users (WorkerID, Username)
With the correct relationships defined, how do I enforce the predication that a User's Username is unique in the company where its worker is in?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为此,您可以使用索引视图。
需要打开某些
SET
选项才能修改索引视图的基表,但如果您使用的是 SQL Server 2005+,则默认情况下这些选项是打开的。You can use an indexed view for this
There are certain
SET
options that need to be on for modification of the base tables of indexed views but if you are on SQL Server 2005+ these are on by default.您不能直接这样做,但您确实有几个选项:
稍微对 Users 表进行非规范化并向其中添加 CompanyID。
对
使用插入/更新触发器进行验证。
You can't directly, but you do have a couple options:
Denormalize the Users table a bit and add the CompanyID to it.
Use an insert/update trigger to do the validation.
您还可以考虑:
并确保
WorkerNo
在公司:You may also consider:
and to make sure that
WorkerNo
is unique within the company: