我有一个表table_One
,其中有多个columns(Column1, Column2, Column3, Column4.....)
两个引用 ( Contains PK values for Table_two
) 到另一个表Table_Two
。有没有什么有效的方法来加入这两个表,而不是将 Table_one 加入到 table_Two 多次.br/>
两个表和所需结果集的结构如下。Table_One
我有一个表table_One
,其中有多个columns(Column1, Column2, Column3, Column4.....)
两个引用 ( Contains PK values for Table_two
) 到另一个表Table_Two
。有没有什么有效的方法来加入这两个表,而不是将 Table_one 加入到 table_Two 多次.br/>
两个表和所需结果集的结构如下。Table_One
您是否尝试过为 table2 表起别名并将其两次加入 Table_One,如下所示?
SELECT
t1.PrimaryKey,
c1.ColumnA AS Column1,
c2.ColumnA AS Column2
FROM Table_One t1
JOIN Table_two c1 ON t1.Column1 = c1.ID
JOIN Table_two c2 ON t1.Column2 = c2.ID;
Select Table_One.PrimaryKey,
T2_Column1.ColumnA As Column1,
T2_Column2.ColumnA As Column2
From Table_One
Inner Join Table_Two As T2_Column1
On Table_One.Column1 = T2_Column1.ID
Inner Join Table_Two As T2_Column2
On Table_One.Column2 = T2_Column2.Id
基本上,您加入表 2 两次。当你这样做时,你必须至少给其中一个起别名,这样 SQL 才不会混淆。作为实践问题,通常最好将两者都取别名,这样当您在 6 个月后再次阅读此代码时,会更容易理解。
以下解决方案(SQLFiddle)仅从第二个表中读取行一次:
SET STATISTICS IO ON;
...
PRINT 'Test #1'
SELECT *
FROM
(
SELECT ca.PrimaryKey, ca.[Type], y.ColumnA
FROM @Table1 x
UNPIVOT( Value FOR [Type] IN ([Column1], [Column2]) ) ca
INNER MERGE /*HASH*/ JOIN @Table2 y ON ca.Value = y.ID
) src
PIVOT( MAX(src.ColumnA) FOR src.[Type] IN ([Column1], [Column2]) ) pvt
PRINT 'End of Test #1'
结果:
Test #1
PrimaryKey Column1 Column2
---------- --------- -------
1 ALPHA CHARLIE
2 BETA DELTA
3 CHARLIE ALPHA
4 DELTA CHARLIE
5 ALPHA DELTA
6 CHARLIE ALPHA
7 ALPHA DELTA
8 DELTA CHARLIE
Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table '#65B6F546'. Scan count 1, logical reads 2, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table '#61E66462'. Scan count 1, logical reads 2, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
End of Test #1