需要从具有相同外键的多个表中获取数据

时间:2015-05-09 03:25:45

标签: sql sql-server

我有

  • table-1,InjID(PK)和Name
  • 表{2} Tid(参考)表示InjId(表1)和Name
  • 表3中ID(参考)表示InjID(表1)和Name

表2和表3之间没有任何联系。

我有这样的数据:

表1

________________
InjID     Name
----------------
1         xxxx
2         bbbb
3         cccc
4         yyyy

表2

--------------
TID      Name
--------------
1        A3434
1        R5678
2        G6789

和表3

-------------
ID     Name
-------------
2      89T
2      78P
3      66J

我想要这样的结果:

--------------------------
injid    Table1-name Table2-name table3-name
--------------------------------------------
1         xxxx        A3434        null
1         xxxx        R5678        null 
2         bbbb        G6789        89T
2         bbbb        null         78P
3         cccc        null         66J
4         yyyy        null         null

1 个答案:

答案 0 :(得分:2)

我想你只想要一个OUTER JOIN

select t1.injid, t1.name, t2.name, t3.name
from table1 t1
  left join table2 t2 on t1.InjID = t2.tid
  left join table3 t3 on t1.InjID = t3.id

执行如下:

SQL>select * from table1;
      InjID name
=========== ==========
          1 xxxx
          2 bbbb
          3 cccc
          4 yyyy

                  4 rows found

SQL>select * from table2;
        TID name
=========== ==========
          1 A3434
          1 R5678
          2 G6789

                  3 rows found

SQL>select * from table3;
         ID name
=========== ==========
          2 89T
          2 78P
          3 66J

                  3 rows found

SQL>select t1.injid, t1.name, t2.name, t3.name
SQL&from table1 t1
SQL&  left join table2 t2 on t1.InjID = t2.tid
SQL&  left join table3 t3 on t1.InjID = t3.id;
      InjID name       name       name
=========== ========== ========== ==========
          1 xxxx       A3434      -
          1 xxxx       R5678      -
          2 bbbb       G6789      89T
          2 bbbb       G6789      78P
          3 cccc       -          66J
          4 yyyy       -          -

                  6 rows found

使用空值。够好吗?

相关问题