【问题标题】:how to combine plsql select statement with different column and different where condition如何将plsql select语句与不同的列和不同的where条件结合起来
【发布时间】:2021-09-13 07:06:12
【问题描述】:

很抱歉有虚拟表名,但我想将这两个查询组合在一个选择视图中。我尝试过 UNION 和 CROSS JOIN 运算符,但我发现两者都有问题。两个 Qyuery 共享相同的表,所以我给的表名相同,只有别名不同。 由于每个表中有很多列,而且查询也有点长,所以无法编写整个查询,但我的查询看起来只是这样 谁能建议解决这个问题的方法?

select 
    a.col1,
    b.col2,
    c.col3,
    d.col4,
    e,col5
from 
    table1 a, table2 b, table3 c, table4 d, table5 e
where 
    a.col1 = b.col2 
and b.col2 = e.col3(+)
and d.col5 = b.col6
and a.col7 = 'Active';

select 
    a.col5,
    b.col6,
    c.col7
from
    table1 a, table2 b,table5 c 
where 
    b.col2 = c.col3
    and a.col7 = 'Active';

【问题讨论】:

    标签: plsql oracle-sqldeveloper plsqldeveloper


    【解决方案1】:

    UNION - 如果它满足您的需求 - 会起作用; “缺失”的列应替换为NULL占位符。像这样的:

    select 
        a.col1,
        b.col2,
        c.col3,
        d.col4,
        e,col5
    from 
        table1 a, table2 b, table3 c, table4 d, table5 e
    where 
        a.col1 = b.col2 
    and b.col2 = e.col3(+)
    and d.col5 = b.col6
    and a.col7 = 'Active'
    union 
    select 
        a.col5,
        b.col6,
        c.col7,
        null,                             --> this
        null                              --> and this
    from
        table1 a, table2 b,table5 c 
    where 
        b.col2 = c.col3
        and a.col7 = 'Active';
    

    另外,考虑

    • 使用UNION ALL 而不是UNION(可能会更快,因为UNION 会删除重复项)
    • CASTNULLs 到适当的数据类型,例如cast(null as varchar2(10)) 因为 - 使用 UNION 时 - 选择必须匹配列数,而列必须匹配数据类型。 Oracle 将隐式尝试将 NULL 转换为适当的数据类型,但是 - 为什么不控制它?

    【讨论】:

    • 我的原始查询表每个有 60-70 列,我的第一个查询有 27 个不同的列,而第二个查询有 20 个列......所以这样做很容易吗?
    • 我想打字更快。
    • 抱歉打字慢!
    • 我的 where 条件在两个查询中都不同,您有什么想法来解决这个问题吗?请帮忙!
    猜你喜欢
    • 2013-06-10
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 2012-12-12
    • 2015-07-11
    • 2020-02-14
    • 2014-04-05
    • 2018-07-27
    相关资源
    最近更新 更多