tags:

views:

63

answers:

2

Hello,

I have 3 tables: A, B and C. Table A is in relation (n:1) with B and with C. Typically I store in A the B.Id (or the C.Id) and the table name.

e.g.

A.ParentId = 1 A.TableName = "B"

A.ParentId = 1 A.TableName = "C"

A.ParentId = 2 A.TableName = "B"

Is it a good solution? Are there any other solutions?

Thanks in advance

+1  A: 

Why not 2 parentid columns?

A.ParentIdB = 1
A.ParentIdC = 3

Sander Rijken
Because it is not scalable: suppose to have n tables related to A, you have to create n columns.
A: 

Another possibility is to introduce another table Content (D) that serves as a "supertype" to Posts and Images. Then a row in Comments (A) would reference a primary key in Content as would each row in Posts (B) and Images (D). Any common fields in Posts and Images would be moved to Content (perhaps "title" or "date") and those original tables would then only contain information specific to a post or image (perhaps "body" or "resolution"). This would make it easier to perform joins than having the table names in a field, but it does mean that a real-world entity could be both a post and a comment (or indeed, be multiply a post or comment!). Really, though, it depends on the situation that you're trying to model.

Rich
It sounds good. But help me to understand. Suppose to have 4 tables: Comments (A), Supertype (D), Posts (B) and Images (C). It is simple to retrieve all comments related, for example, to a post but if I should need to retrieve specific information (from Posts (B) or Images (C)) by a comment?
You could do that by using an inner join, couldn't you?
Rich
Suppose you want to select a specific information (stored in B or C or ...) related to the last record in A. How could you do that?
If you don't know whether A is attached to a B or a C, you'll have to do something like A inner join D left outer join B left outer join C, where the joins are on the appropriate keys, and then look at the fields in your application to work out whether the A is linked to a B or C. You can get the last record by ordering by the key or insertion date of A in the appropriate order and taking the top 1 row.
Rich