开发者

Querying a child table in SQL Server [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.

Want to improve this question? Add details and clarify the problem by editing this post.

Closed 9 years ago.

Improve this question

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 Table2 and Table3 are directly defined by Table1; that is, it doesn't make sense to have a Table2 record without a parent Table1 record. Likewise, it looks like Table4 only makes sense when both Table2 and Table3 exist. If this is true, then Table2, Table3, and Table4 should have compound primary keys along these lines:

Table2
-------------
Table1ID     -- consider renaming this in Table1 so that the same name is used 
                throughout
RecordNumber -- unique within a given Table1ID; this is only needed if one of 
                your other two columns cannot serve as a unique value within 
                Table1ID, which I'm guessing one of them can

Then you'd do something similar for Table3. Then, for Table4, you'd have:

Table4
-------------
Table1ID
Table2RecordNumber
Table3RecordNumber

As the primary key, then set up two foreign keys, one to Table2 on (Table1ID, Table2RecordNumber) and one to Table3 on (Table1ID, Table3RecordNumber). This allows you to ensure that your Table4 records always link to Table2 and Table3 records with the same Table1ID, and it simplifies the join in the original query so that it doesn't have to go through Table2 or Table3 to find a valid record in Table4.


SQL JOIN

http://www.w3schools.com/sql/sql_join.asp

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜