views:

86

answers:

2

Hi all,

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)

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.

thanks Leonardo

+1  A: 

What you are trying to do is in most cases an anti pattern and design mistake. Just create the different tables instead of views.

There are some rare cases where this kind of design makes sense. In this kind include the xcode field in the primary key/ foreign key. So your entity will look like this:

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

You then can create check constraints to enforce role_xcode='r' and title_xcode='p'

(sorry I don't know if they are standard, they do exist in oracle and are so simple that I'd expect them on other rdbms's as well)

Jens Schauder
+1  A: 

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.

The advantages of a table per code are:

  1. Foreign keys. As you have already spotted it is not possible to enforce compliance to permitted values through foreign keys with a single table. Using check constraints is an alternative approach but it has a higher maintenance cost.
  2. Performance. Code lookups are not normally a performance bottle neck, but it undoubtedly helps the optimizer to make sensible decisions about execution paths if it knows it is retrieving records from a table with four rows rather than four hundred.
  3. Code groups. Sometimes we want to organise a code into sub-divisions, usually to make it easier to render complex lists of values. If we have a table per code we have more flexibility when it comes to structure.

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.

APC