【问题标题】:Missing data from Left JOINLeft JOIN 中缺少数据
【发布时间】:2012-06-01 11:05:14
【问题描述】:

我有两张桌子要连接在一起。

SELECT Col3, tab1.Col1, tab1.Col2 FROM
    (SELECT Col1,Col2 
    FROM Table1
    GROUP BY Col1,Col2) tab1
LEFT JOIN
    (SELECT Col3, Col1, Col2
    FROM Table2
    GROUP BY Col3, Col1, Col2) tab2
ON tab2.Col2 = tab1.Col2 AND tab2.Col1 = tab1.Col1

目前,对于 Table2 中不存在的 Table1 中的行,我返回 Col3 为 Null 的行。由于我基于 Col3 对数据进行分组,如果我能以某种方式获得 Col3 的值而不是 Null 会很好.....

这可能吗?

所以我试图返回 col1 和 col2 的每个可能的组合,每个 col3 的值。问题是当 col3 不包含 col1,col2 的特定组合时,我得到 col3 的空值...

【问题讨论】:

  • 你为什么使用LEFT JOIN
  • 您是否真的想显示 Col1 和 Col2 的每个组合的 Col3 的所有可能值,在 Table2 中找不到 (col1, col2, col3) 的地方产生零?如果你这样做,你应该解释实际的表格。

标签: sql sql-server left-join


【解决方案1】:

假设 Col3 是某种类别,并且是 category 表的主键,您可以这样做:

select Category.Col3,
       tab1.Col1,
       tab1.Col2,
       sum (tab2.YourAggregate) SumOfSomething
 -- Take all categories
  from Category
 -- Cartesian product with Tabl1
 cross join Table1 tab1
 -- Find matching records in Table2, if they exist
  left join Table2 tab2
    on Category.Col3 = Tab2.Col3
   and Tab1.Col1 = Tab2.Col1
   and Tab1.Col2 = Tab2.Col2
 group by Category.Col3,
       tab1.Col1,
       tab1.Col2

Cross join 生成所涉及表的笛卡尔积,检索可能在 Table2 中找不到的 Col3。

【讨论】:

    【解决方案2】:

    LEFT JOIN 将在右表中产生空值,在左表中找不到 Col1 和 Col2 的匹配项。这是预期的行为。

    如果您在编写不同的查询时需要帮助,则必须发布您的数据结构和一些示例数据以供使用。

    【讨论】:

      【解决方案3】:

      只需切换表(或使用右连接):

      SELECT tab2.Col3, tab2.Col1, tab2.Col2 FROM
        (SELECT distinct Col3, Col1, Col2 FROM Table2) tab2
      LEFT JOIN
        (SELECT distinct Col1,Col2  FROM Table1) tab1
      ON tab2.Col2 = tab1.Col2 AND tab2.Col1 = tab1.Col1
      

      【讨论】:

        猜你喜欢
        • 2020-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多