【问题标题】:SQL query to combine tables without joiningSQL查询组合表而不加入
【发布时间】:2020-07-14 18:36:39
【问题描述】:

SQL 连接似乎总是合并数据,但我需要创建一个共享列名的不同表的报告。因此,对于一个表中的所有值,另一个表的所有值都将为空白,反之亦然。见附件

.

附:仍然是新手 - 非常感谢任何帮助更恰当地措辞这个问题/标题。

【问题讨论】:

    标签: sql


    【解决方案1】:

    您正在寻找UNION ALL

    select project, null as milestone, null as change
    from projects
    union all
    select project, milestone, null as change 
    from milestones
    union all
    select project, null as milestone, change
    from changes
    

    unionunion all 的区别在于后者不会删除输出中的重复行。

    【讨论】:

      【解决方案2】:

      根据您的结果,您似乎想要:

      select p.project, null as milestone, null as change
      from projects p
      where not exists (select 1 from milestones m where m.project = p.project) and
            not exists (select 1 from changes c where c.project = p.project)
      union all
      select m.project, m.milestone, null as change 
      from milestones
      union all
      select c.project, null as milestone, c.change
      from changes;
      

      这是因为你的结果没有行:

      A     NULL     NULL
      

      因此,当其他表中没有对应的行时,您似乎只想要 projects 中的一行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        • 2021-01-21
        • 1970-01-01
        • 2014-06-01
        • 2011-10-10
        • 2019-06-13
        相关资源
        最近更新 更多