简体   繁体   中英

Joining tables with Foreign Keys

How do I INNER JOIN a table that contains 2 foreign keys as its primary keys?

CREATE TABLE table1 (table1ID CHAR(4));
CREATE TABLE MEM_INSTR (table2ID CHAR(4));
CREATE TABLE table3 (table1ID CHAR(4), table2ID CHAR(4));

Assuming you want to just join everything together as keys suggest...

SELECT *
FROM table1
INNER JOIN table3 on table3.table1ID = table1.table1ID
INNER JOIN MEM_INSTR on MEM_INSTR.table2ID = table3.table2ID

But let's say that you have this scenario.

CREATE TABLE Table1 (
    Table1ID NUMBER, 
    Generation NUMBER, 
    ... 
);

CREATE TABLE Table2 (
    Table2ID NUMBER, 
    Table1ID NUMBER, 
    Table1Generation NUMBER, 
    ...
);

Let's say for argument's sake that Table1 can have multiple records with the same Table1ID, and Generation is used as a secondary key. And you need to join a Table2 record to the correct single Table1 record. You can expand the ON clause the same way you would expand a WHERE clause.

SELECT *
FROM table1 t1
INNER JOIN table2 t2 
    ON t2.table1id = t1.table1id 
    AND t2.table1generation = t1.generation

You join it like you usually do, nothing really special about that. So you go something like this:

SELECT ...
FROM table1
INNER JOIN table3 ON table3.table1ID = table1.table1ID
INNER JOIN MEM_INSTR ON MEM_INSTR.table2ID = table3.table2ID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM