I have a database in a SQL Server 2008 database. My database model forms a diamond pattern with four tables. Those four tables are defined as follows:
Table1
- ID
- Name
- AddedBy
Table2
- ID
- Table1ID
- Name
- Type
Table3
- ID
- Table1ID
- Name
Table4
- ID
- Table2ID
- Table3ID
- Age
I am currently getting all of the Table1 records for a specific user by using the AddedBy field. This query looks like this:
SELECT
*
FROM
[Table1] t1
WHERE
t1.[AddedBy]=@someuser
Now, I need to get the Age value from the first Table4 record that is somehow associated with Table1. How do I do this? I keep getting confused with the query.
Thank you for any help you can provide!
This is a classic illustration of how compound primary keys can allow you to more accurately express what you want your database to do.
Given the model that you have, it appears that
Table2andTable3are directly defined byTable1; that is, it doesn’t make sense to have aTable2record without a parentTable1record. Likewise, it looks likeTable4only makes sense when bothTable2andTable3exist. If this is true, thenTable2,Table3, andTable4should have compound primary keys along these lines:Then you’d do something similar for
Table3. Then, forTable4, you’d have:As the primary key, then set up two foreign keys, one to
Table2on (Table1ID, Table2RecordNumber) and one toTable3on (Table1ID, Table3RecordNumber). This allows you to ensure that yourTable4records always link toTable2andTable3records with the sameTable1ID, and it simplifies the join in the original query so that it doesn’t have to go throughTable2orTable3to find a valid record inTable4.