Skip to content
Advertisement

how to disallow custom lists to have elements from different base lists

I have the following model:

  1. BASE_LIST: in this table we store base lists. Base list can be for example the list of cities in a continent, types of automobiles in a shop etc.

  2. ELEMENT: in this table we store the elements of base lists. For example the cities and the car types are here (Budapest, London, Paris, Opel, Bmw, Audi)

  3. CUSTOM_LIST: in this table we store customizations of the lists. The customization means filtering. For example there can be a custom list called ‘european cities’ which is a subset of the cities. Or pricey cars which is a subset of the cars. A custom list must have exactly one parent – base list, and only elements from that base list can be in it.

The current representation is this:

enter image description here

The relation between BASE_LIST and ELEMENT is a one to many relation (an element can be a part of only one base list, but a base list can have many elements).

The relation between BASE_LIST and CUSTOM_LIST is a one to many relation, each custom list must have exactly one “parent list”.

The relation between the CUSTOM_LIST and ELEMENT is a many to many relationship, because

  • an element can be part of more than one custom lists: for example a car may be in a custom list called “pricey cars” and in an other custom list called “unreliable cars” too.
  • and a custom list of course can have multiple elements, therefore the many to many relation.

The problem is that this structure allows a custom list with elements from different base lists.

We would like to prohibit this. In other words a custom list with elements from the “cars” base list is OK, a custom list with elements from the “cities” list is OK, but a custom list with cars and cities mixed is NOT OK.

Is there a way to prohibit such mixed lists with standard constraints (no stored procedures etc)?

I have created a fiddle for this:

http://sqlfiddle.com/#!4/40801/2


DDL:

Problem:

Advertisement

Answer

In order to prevent custom elements from different lists, you’ll need to use composite keys. These will travel down both the relationships brachches and will enforce each custom element to belong to a single base list.

For example you can do:

In particular, notice both foreign keys in the last table share the same column base_list_id. That enforces the rule you want.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement