数据库设计:其他实体引用的“代码”表 [英] database design: a 'code' table that get referenced by other entities

查看:107
本文介绍了数据库设计:其他实体引用的“代码”表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建数据库,这是一个简单的练习,它可以托管在任何数据库服务器上,因此,我试图使事情保持尽可能的标准。基本上,我想做的是被其他实体引用的代码表。我会解释:

I am building a database as a simple exercise, it could be hosted on any database server, so I am trying to keep things as much standard as possible. Basically what I would like to do is a 'code' table that get referenced by other entities. I explain:

xcode
id code
r  role
p property

code
r admin
r staff
p title
....

然后我想要一些视图,例如:

then I would like to have some view like:

role (select * from code where xcode='r')
r admin
r staff

property (select * from code where xcode='p')
p title

然后,假设我们有一个实体

then, suppose we have an entity

myentity
id - 1
role - admin (foreign key to role)
title - title (foreign key to property)

很明显,我无法为视图创建外键,但这是要告诉我的主意。我怎么能尽可能地使用标准sql语法来反映这种行为,然后作为第二种选择,使用数据库附加功能,例如触发器ecc ...?

Obviously I cannot create foreign key to a view, but this is to tell the idea I have in mind. How can I reflect such behaviour using whenever possible, standard sql syntax, then as a second option, database additional features like trigger ecc... ?

因为我告诉我角色和标题是代码的外键,而不是视图,没有什么可以阻止我在标题字段中插入角色。

Because if I tell that role and title in myentity are foreign key to 'code', instead of the views, nothing would stop me to insert a role in title field.

推荐答案

我在一个系统中使用了所有代码的单个表,而在每个代码中使用一个表的系统。我绝对更喜欢后一种方法。

I have worked on systems with a single table for all codes and others with one table per code. I definitely prefer the latter approach.

每个代码表的优点是:


  1. 外键。正如您已经发现的那样,不可能通过具有单个表的外键来强制遵守允许的值。使用检查约束是一种替代方法,但维护成本较高。

  2. 性能。代码查找通常不是性能瓶颈,但是,如果它知道它是从具有四行而不是四百行的表中检索记录,则无疑可以帮助优化器做出明智的决策。

  3. 代码组。有时我们希望将代码组织为细分,通常是为了更轻松地呈现复杂的值列表。如果我们每个代码都有一个表,那么在结构上就会有更大的灵活性。

此外,我注意到您希望能够在任何数据库服务器上部署。在这种情况下,请避免触发。在大多数情况下,触发器通常是个坏消息,但是它们具有特定于产品的语法。

In addition I notice that you want to be able to deploy "on any database server". In that case avoid triggers. Triggers are usually bad news in most scenarios, but they have product-specific syntax.

这篇关于数据库设计:其他实体引用的“代码”表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆