views:

208

answers:

2

I have an inheritance relationship in my database, where I have a parent table (Table A) that is basically a sequence of auto-incrementing integers (Id column). From here, I have several tables (Table B,C & D) that also have an Id column, which is a foreign key to the Id column in Table A.

Now my question is, if I have the Id, what is the most efficient way I can go about getting the correct row from table B, C, or D?

EDIT: There will be only ONE row with the Id in either table B, C, or D (there will not be a matching row in the other 2).

A: 

With a join.

SELECT 
  a.id, b.somecol, c.somecol, d.somecol
FROM 
  sometable a
INNER JOIN 
  btable b on b.id = a.id
INNER JOIN
  ctable c on c.id = a.id
INNER JOIN
  dtable d on d.id = a.id

If you're not sure that one of the child tables contains data related to the parent table, use an outer join instead of an inner join.

Ken White
-1 for a query that never returns anything
cdonner
Only ONE of the tables will contain any information of interest, so I don't believe this will work
+1 because this was posted BEFORE the OP clarified the situation of only 1 table having the ID. Date/time posted, kids. Date/time posted.
HardCode
How to query the concrete table when only the parent table id is known? - I thought the question was pretty clear.
cdonner
So you're telling me that knowing the PK for table a, with that field as a FK in table B, will make it impossible to find the record in table B?
HardCode
Correct - If the record is in table C, you will not find it in table B. Not that this makes any sense, but it seems that questioningquerier wants to do it this way.
cdonner
True. But my original point was, the OP did NOT specify that the ID is in only one of the other three tables. Hence, data/time of this post and the last OP edit.
HardCode
Thanks for the downvote. Apparently whoever did that can't read, as I specifically discussed only one table in the last paragraph. That's OK, though. I appreciate it.
Ken White
@HardCode: Thanks for reading before voting.
Ken White
A: 

You could use union queries ... i.e.:

select 'TABLE B', a_id from b where a_id = 1
UNION
select 'TABLE C', a_id from c where a_id = 1
UNION
select 'TABLE D', a_id from d where a_id = 1;

This would give you a list of tables with an a_id of 1, while also showing the table it resided in.

If all 3 tables have the same structure, you could do something similar:

select b.* from b where a_id = 1
UNION
select c.* from c where a_id = 1
UNION
select d.* from d where a_id = 1;
Jess