从多对多表中获取所有相关数据

时间:2016-12-22 07:54:53

标签: sql oracle select

这是我从M-M表中获取Table2的所有数据的选择。我必须从表中获取数据ID_TABLE1_FK=3值。

    Select s1.* from TABLE2 s1 
    JOIN TABLE3 s2 ON s2.ID_TABLE2_FK = s1.ID_TABLE2_PK
    WHERE s2.ID_TABLE1_FK=3;

   'this query returns me data from table1 same way - I need to combine
   'them both in 1 row, that is desired output
    Select a1.* from TABLE1 a1 
    JOIN TABLE3 s2 ON s2.ID_TABLE1_FK = a1.ID_TABLE1_PK
    WHERE s2.ID_TABLE1_FK=3;

现在,我想在同一个查询中获取Table1的所有数据。怎么样?

这些是我的桌子设计:

    M-M table:
    ID_TABLE3_PK
    ID_TABLE1_FK
    ID_TABLE2_FK

    TABLE1:
    ID_TABLE1_PK
    Name
    Surname

    TABLE2:
    ID_TABLE2_PK
    Street
    Address

DESIRED OUTPUT (with only ID_TABLE1_FK=3):

Name,Surname,Street,Address

1 个答案:

答案 0 :(得分:1)

您可以在table1上加入table2table3

SELECT s1.*, a1.* 
FROM   TABLE2 s1 
JOIN   TABLE3 s2 ON s2.ID_TABLE2_FK = s1.ID_TABLE2_PK
JOIN   TABLE1 a1 ON s2.ID_TABLE1_FK = a1.ID_TABLE1_PK
WHERE  s2.ID_TABLE1_FK=3;