My application has several tables: a master OBJECT table, and several
tables for storing specific kinds of objects: CAT, SHOE and BOOK.
Here’s an idea of what the table columns look like:
object
object_id (primary key)
object_type (string)
cat
cat_id (primary key)
object_id (foreign key)
name (string)
color (string)
shoe
shoe_id (primary key)
object_id (foreign key)
model (string)
size (string)
book
book_id (primary key)
object_id (foreign key)
title (string)
author (string)
From the user’s point of view, each specific object is primarily identified
by its name, which is a different column for each table. For the CAT table
it’s name, for the SHOE table it’s model, and for the BOOK table it’s
title.
Let’s say I’m handed an object_id without knowing in advance what kind of
object it represents — a cat, a shoe or a book. How do I write a
SELECT statement to get this information?
Obviously it would look a little like this:
SELECT object_type,name FROM object WHERE object_id = 12345;
But how do I get the right contents in the “name” column?
It seems like you’re describing a scenario where the user’s view on the data (objects have names, I don’t care what type they are) is different from the model you’re using to store the data.
If that is the case, and assuming you have some control over the database objects, I’d probably create a
VIEW, allowing you to coalesce similar data for each type of object.Example on SQL Server:
You can then
SELECT name FROM object_names WHERE object_id = 12345, without concerning yourself with the underlying column names.