views:

85

answers:

2

What I mean is, If I had the following schema:

create table tableA(
    A_id   number not null primary key
);

create table tableB(
    B_id   number not null primary key,
    A_id   number not null references tableA(A_id),
    B_data text   not null
);

create table tableC(
    C_id   number not null primary key,
    A_id   number not null references tableA(A_id),
    C_data text   not null
);

If I wanted to retrieve B_data and C_data using the relationships described here, is there any difference between the following:

select
    b.B_data,
    c.C_data
from
    tableB b
    inner join tableC c
        on b.A_id = c.A_id;

and:

select
    b.B_data,
    c.C_data
from
    tableB b
    inner join tableA a
        on b.A_id = a.A_id
    inner join tableC c
        on a.A_id = c.A_id;

I suspect that most databases will optimise either query to be the same, but are there cases where the foreign key constraints to tableA will make joining via tableA much more efficient? Are there any cases where these queries could produce different results?

+1  A: 

The first version works fine. Foreign key relationships are about referential integrity and don't necessarily have to be traversed as they are defined.

cletus
+1  A: 

You may as well join them directly. Foreign key constraints don't do anything to make joins more efficient; indexes do that, which (depending on DBMS) may be a separate matter from foreign keys. Either way, if there's an index to work with, you have it regardless of whether you're going by your foreign key.

chaos