I am working on a php project that needs to store information about various buildings and will store different types of information depending on the type of the building:

Class Building {
    var $location
    var $name

The Building class will be extended by classes like, House and Office so the classes will look like this (just an example)

Class House Extends Building {
    var $numRooms;
    var $numBathrooms;

Class Office extends Building {
    var $offices;
    var $sqfoot;

The question is, how should this be represented in a database (im using MySQL, if it matters). Should I use the building table to store the location and name and then create a table for each of the other classes to hold 'extended' variables? Or do I create a table for each class? or should the building table have columns for all the variables that can be in the other classes?

Accepted Answer

I would strongly recommend that you look at the Class Table Inheritance pattern as defined by Martin Fowler.

This design pattern creates a single table that holds the data that is common to all Buildings for example and then requires a separate table for any data that is related to a specific type of building. One thing that I find helpful is to store a 'type' field in the parent table so that you know what type of entity you have without having to search the child tables for corresponding records.

I would recommend that unless you have a very specific, well-defined reason to use an Entity-Attribute design, that you avoid it. For one thing it becomes impossible when using this type of design to take advantage of constraints on the database to control what inputs are required and what types of values are allowed. For another, it will drastically slow down any queries that need to pull data out of those types of fields because data stored in those fields cannot be indexed like you would typically.

Written by Noah Goodrich
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki