CREATE VIEW twotables AS
SELECT a.col1, a.col2, a.col3, a.col4, b.col5, b.col6, b.col7, a.col8
FROM table1 a
JOIN table2 b ON a.col1=b.col1 and a.col2=b.col2 and a.col3=b.col3 and a.col4=b.col4
CREATE VIEW twotables as
SELECT a.col1, a.col2, a.col3, a.col4, b.col5, b.col6, b.col7, a.col8
FROM (select distinct col1, col2, col3, col4 from table1
union
select distinct col1, col2, col3, col4 from table2
) as k
LEFT JOIN table1 a ON a.col1=k.col1 and a.col2=k.col2 and a.col3=k.col3 and a.col4=k.col4
LEFT JOIN table2 b ON b.col1=k.col1 and b.col2=k.col2 and b.col3=k.col3 and b.col4=k.col4
在这里,我们首先获得所有“键”的列表,然后我们将连接添加到两个表中 .
2
如果您不想使用VIEW,则可以通过以下方式创建表:
WITH Data
AS ( SELECT col1 ,
col2 ,
col3 ,
col4 ,
NULL AS col5 ,
NULL AS col6 ,
NULL AS col7 ,
col8
FROM table1
UNION ALL
SELECT col1 ,
col2 ,
col3 ,
NULL AS col4 ,
col5 ,
col6 ,
col7 ,
NULL AS col8
FROM table2
)
SELECT *
INTO table3
FROM Data;
2 回答
您可能想要一个视图 - 这是您在大多数平台上制作视图的方法 .
您可能希望也可能不希望联接中的这些列 .
许多人在做这样的事情时遇到的另一个问题是他们在两个表中都有不同的col1,col2,col3和col4记录 . 然后你需要这样的事情:
在这里,我们首先获得所有“键”的列表,然后我们将连接添加到两个表中 .
如果您不想使用VIEW,则可以通过以下方式创建表: