【问题标题】:Single SELECT combining multiple JOINs单个 SELECT 组合多个 JOIN
【发布时间】:2015-08-27 19:26:28
【问题描述】:

我试图弄清楚如何编写一个 SQL 查询来返回另外两个 SELECT 语句的结果,每个语句都有自己的 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 语句来获取数字:

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,但我知道这比我做的要容易得多。非常感谢。

【问题讨论】:

    标签: select join


    【解决方案1】:

    您可以在join 操作中使用没有where 子句和case 语句的单个select 语句。比如:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-27
      • 2011-03-03
      • 2015-06-03
      • 2015-12-28
      • 2013-06-11
      • 2010-09-27
      相关资源
      最近更新 更多