SQL使用where子句连接多个表

时间:2014-04-11 08:56:11

标签: sql sql-server

我想写一个sql语句:

Select * FROM table1
inner join table2 AS t2
  ON 
inner join table3 AS t3
  ON
inner join table4 AS t4
  ON
Where FK_Client_ID = 4

所有表都有共同的客户端ID。所以不确定在ON上做什么。

是不是ON t2.FK_Client_ID = ......不确定。

所以我只想要那些具有共同FK_Client_ID的表中的所有数据。

4 个答案:

答案 0 :(得分:0)

试试这个

Select * FROM table1 t1
inner join table2 AS t2
  ON t2.FK_Client_ID = t1.FK_Client_ID
inner join table3 AS t3
  ON t3.FK_Client_ID = t1.FK_Client_ID
inner join table4 AS t4
  ON t4.FK_Client_ID = t1.FK_Client_ID
Where t1.FK_Client_ID = 4

答案 1 :(得分:0)

如果您的外国字段名称为"FK_Client_ID"且表1中的主键为"Client_ID"

Select * FROM table1
inner join table2 AS t2
  ON  t2.FK_Client_ID = table1.Client_ID
inner join table3 AS t3
  ON  t3.FK_Client_ID = table1.Client_ID
inner join table4 AS t4
  ON  t4.FK_Client_ID = table1.Client_ID
Where table1.Client_ID = 4

由于您正在使用内部联接,无论您是使用table1还是其他任何内容加入

答案 2 :(得分:0)

Select * FROM table1 t1 inner join table2 t2
     ON t1.FK_Client_ID = t2.FK_Client_ID 
        inner join table3 t3
     ON t1.FK_Client_ID = t3.FK_Client_ID
         inner join table4 t4
     ON t1.FK_Client_ID = t4.FK_Client_ID
 Where t1.FK_Client_ID = 4

答案 3 :(得分:0)

Select *,
     (Select FK_Client_ID from table2 where FK_Client_ID = t1.FK_Client_ID  )As TID1,
     (Select FK_Client_ID from table3 where FK_Client_ID = t1.FK_Client_ID  )As TID2,
     (Select FK_Client_ID from table4 where FK_Client_ID = t1.FK_Client_ID  )As TID3 
FROM table1 t1