单个SELECT组合多个JOIN

时间:2015-08-27 19:26:28

标签: select join

我试图弄清楚如何编写一个返回两个其他SELECT语句结果的SQL查询,每个语句都有自己的JOIN。这是场景:

Table1可能在T1Number和/或T1State列中具有NULL值。表2可能包含具有匹配数字或状态的行。我想要Table1中的所有行,但是想要在状态匹配时用T2Number填充任何NULL T1Number,并在数字匹配时用T2State填充任何NULL T1State。我不希望Table2中的行没有匹配的状态或数字:

Table1:                         Table2:

Name  T1Number  T1State         T2Number  T2State
----  --------  -------         --------  -----
Joe   1         NULL            1         MA
Bob   NULL      CA              2         CA
Dan   NULL      NULL            3         FL
Sam   4         NY              4         NY
Ray   5         TX              8         PA

所以我有一个SELECT语句来获取Number:

SELECT 
  Table1.Name,
  Table1.T1Number,
  Table1.T1State,
  Table2.T2Number,
  Table2.T2State
FROM Table1
INNER JOIN Table2 ON Table2.T2State = Table1.T1State
WHERE (Table1.T1Number IS NULL OR Table1.T1State IS NULL)

Result:

Name  T1Number  T1State  T2Number  T2State
----  --------  -------  --------  -------     
Bob   NULL      CA       2         CA

获取状态的另一个SELECT语句:

SELECT
  Table1.Name,
  Table1.T1Number,
  Table1.T1State
  Table2.T2Number
  Table2.T2State
FROM Table1
INNER JOIN Table2 ON Table2.T2Number = Table1.T1Number
WHERE (Table1.T1Number IS NULL OR Table1.T1State IS NULL)

Result:

Name  T1Number  T1State  T2Number  T2State
----  --------  -------  --------  -------     
Joe   1         NULL     1         MA

如何编写一个组合的SELECT语句,为我提供以下所需的结果?

Name  Number  State
----  ------  -----     
Joe   1       MA 
Bob   2       CA
Dan   NULL    NULL
Sam   4       NY
Ray   5       TX

我假设我需要一个包含SELECT语句,在Table1和上述查询的并集之间执行LEFT JOIN,但我知道这比我做的更容易。非常感谢提前。

1 个答案:

答案 0 :(得分:0)

您可以在select操作中使用不带where子句和case语句的单个join语句。类似的东西:

SELECT t1.Name
     , CASE WHEN t1.Number is null then t2.Number else t1.Number END as Number
     , CASE WHEN t1.State is null then t2.State else t1.State end as State
FROM Table1 t1
LEFT JOIN Table2 t2 
ON CASE WHEN t1.Number is null THEN t1.State 
        ELSE CONVERT(varchar(1), t1.Number) END
    = CASE WHEN t1.Number is null THEN tab2.State 
           ELSE CONVERT(varchar(1), t2.Number) END