如何基于SQL Server中的主表列值加入表?

时间:2018-02-26 10:11:54

标签: sql sql-server-2012

我有以下3个表格:

MAIN_TABLE:

id,name,table_type
1a,sas,1
2a,saw,1
3a,sdd,2

inst_table

id,inst_name,rating
1a,sdsdf,3
2a,erer,4

indv_table

id,ind_name,rating
3a,gbgbg,3
5a,gff,4

如何根据main_table column:'table_type'加入子表?

即如果main table column: table_type = 1,则必须加入table:'inst_table'其他table:'indv_table'

2 个答案:

答案 0 :(得分:2)

SELECT *
  FROM main_table t1
    INNER JOIN inst_table t2 ON T1.ID = T2.ID where t1.table_type=1
UNION ALL
  SELECT *
  FROM main_table T1
    INNER JOIN indv_table T3 ON T1.ID = T3.ID where t1.table_type=2

答案 1 :(得分:1)

您可以将两个子表连接到main_table:

proc sql;
select m.*, i.*, d.* 
from main_table as m 
left join inst_table as i on m.id=i.id and m.table_type = 1
left join indv_table as d on m.id=d.id and m.table_type ne 1
;
quit;