【问题标题】:Which type of join can I use to reproduce these results我可以使用哪种类型的连接来重现这些结果
【发布时间】:2009-12-21 19:51:13
【问题描述】:

我有以下包含此数据的视图

ActivityRecId RegionRecId IsExcluded
1             null        1
2             null        1
3             1           1
3             2           1
4             1           1
5             null        0

我想做的是将区域表加入到上面的视图中以获取以下记录。

ActivityRecId RegionRecId IsExcluded
1             null        1
2             null        1
3             1           1
3             2           1
3             3           0
3             4           0
4             1           1
4             2           0
4             3           0
4             4           0
5             null        0

区域表有以下列:

  • RegionRecId
  • 地区名称

任何建议。如果您需要任何其他信息,请告诉我。

--------------------- CORRECT QUESTION ------------------------
ActivityRecId RegionRecId IsExcluded
    1             null        1
    2             null        1
    3             1           1
    3             2           1
    3             3           0
    3             4           0
    4             1           1
    4             2           0
    4             3           0
    4             4           0
    5             1           0
    5             2           0
    5             3           0
    5             4           0

如果它更容易,活动 1 和 2 也可以列出所有区域。

谢谢,

【问题讨论】:

  • 区域表包含什么?您显示的内容看起来更像是一个联合而不是一个联接。
  • 区域表只显示了 RegionRecId 和 RegionName
  • 没有意义 - 对于提供的内容,表之间没有连接。您想要视图的所有输出,然后从区域表中列出该视图中不存在的 regionrecid。

标签: sql tsql join


【解决方案1】:

我没有方便的 SQL Server 来测试这个,但会像

select  *
from    myView

union

select  myView.ActivityRecId,
        region.RegionRecId,
        0 as IsExcluded
from    myView cross join region
where   (myView.RegionRecId is not null or myView.IsExcluded = 0)
        and not exists (
            select  null
            from    myView
            where   myView.RegionRecId = region.RegionRecId
        )

做你想要的?

【讨论】:

  • 这对我给你的是正确的。谢谢您的回答。您能否将查询修改为更新后的问题。
  • 我希望我修改后的解决方案现在是正确的,但我再次编写查询但无法对其进行测试。
【解决方案2】:

Here 的很好的参考来看看加入。我认为你需要一个左外连接

【讨论】:

    猜你喜欢
    • 2019-09-22
    • 2019-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多