0
Table A                 
Column A    Column B    Column C    Column D            
1           AA          A1          B1          
2           BB          A2          B2          
3           CC          A3          B3          
4           DD          A4          B4          

Table - B                       
Column E    Column F    Column G    Column H            
1           AA          A1          1234            
2           BB          A2          2345            
3           EE          A3          6767            
4           FF          A4          5555            

Result Table [Joining on Column B and Column C with Column C and Column D that are not primary keys]    
Column B    Column C    Column D    Column H            
AA          A1          B1          1234            
BB          A2          B2          2345            
CC          A3          B3          NULL            
DD          A4          B4          NULL            
EE          A3          NULL            6767            
FF          A4          NULL            5555    

我尝试使用完整的外部连接,但没有看到预期的结果。有任何想法吗?

4

2 回答 2

0

假设您需要加入ColumnBtoColumnFColumnCto ColumnG,您有几个选择来获得上述结果(假设这些是您的预期结果)。

一种选择是使用UNION.

SELECT A.ColumnB, A.ColumnC, A.ColumnD, B.ColumnH
FROM TableA A
  LEFT JOIN TableB B ON A.ColumnB = B.ColumnF AND A.ColumnC = B.ColumnG
UNION 
SELECT B.ColumnF, B.ColumnG, NULL, B.ColumnH
FROM TableB B
  LEFT  JOIN TableA A ON B.ColumnF = A.ColumnB  AND A.ColumnC = B.ColumnG
WHERE A.ColumnB IS NULL

这是SQL Fiddle

另一种选择是使用 COALESCEand FULL OUTER JOIN

SELECT COALESCE(A.ColumnB,B.ColumnF), 
  COALESCE(A.ColumnC,B.ColumnG), A.ColumnD, B.ColumnH
FROM TableA A
  FULL OUTER JOIN TableB B ON A.ColumnB = B.ColumnF AND A.ColumnC = B.ColumnG

还有更多小提琴

它们都应该产生相同的结果。

- 编辑

假设您想要的结果是从输出中删除 NULL 值,那么这样的事情应该可以工作:

SELECT COALESCE(A.ColumnB,B.ColumnF), 
  COALESCE(A.ColumnC,B.ColumnG), 
  COALESCE(A.ColumnD,A2.ColumnD),
  COALESCE(B.ColumnH,B2.ColumnH)
FROM TableA A
  FULL OUTER JOIN TableB B ON A.ColumnB = B.ColumnF AND A.ColumnC = B.ColumnG
  LEFT JOIN TableA A2 ON B.ColumnG = A2.ColumnC
  LEFT JOIN TableB B2 ON A.ColumnC = B2.ColumnG

还有更多小提琴:http ://sqlfiddle.com/#!4/32b3e/1

祝你好运。

于 2013-02-08T01:50:10.203 回答
0

B/C我认为对不同和组合进行预查询会相当简化D/F......然后使用它作为基础来重新加入table AB根据需要获取额外的列。就像是

select
      PreQuery.Col1 as ColumnA,
      PreQuery.Col2 as ColumnB,
      A2.ColumnD,
      B2.ColumnH
   from
      ( select distinct 
              a.ColumnB as Col1,
              a.ColumnC as Col2
           from
              TableA a
        UNION
        select 
              b.ColumnF as Col1,
              b.ColumnG as Col2
           from
              TableB b ) PreQuery
      LEFT JOIN TableA A2
         on PreQuery.Col1 = A2.ColumnB
        AND PreQuery.Col2 = A2.ColumnC
      LEFT JOIN TableB B2
         on PreQuery.Col1 = B2.ColumnF
        AND PreQuery.Col2 = B2.ColumnG

如果您实际上不想NULL显示,请使用

COALESCE( A2.ColumnD, "" )

与 ColumnH 相同

于 2013-02-08T02:37:08.883 回答