【问题标题】:Oracle multiple subqueries return all or nothingOracle 多个子查询全部或全部返回
【发布时间】:2013-03-15 21:16:28
【问题描述】:

我正在发出一个包含多个子查询的查询。如果两个子查询之一失败,则查询不返回任何行。任何返回的唯一方法是两个查询都成功。如果另一个失败,有什么方法可以获得成功的子查询的结果?我已经在查询顶部以及子查询中尝试了 NVL,但均未成功。我知道标量子查询返回 null,但我需要多个值。这是一个可重现的示例查询,我从大得多的东西中提炼出来,其中架构更改/UNION 不是一个选项。(至少我不这么认为)

create table testTBLA(
  product VARCHAR2(10),
  quantity NUMBER,
  code NUMBER
);

INSERT INTO testTBLA VALUES ( 'bottle', 10,3);
INSERT INTO testTBLA VALUES ( 'can', 17, 16);

create table testTBLB(
  fruit VARCHAR2(10),
  asize NUMBER,
  code NUMBER
)

INSERT INTO testTBLB VALUES ( 'melon', 3, 14);
INSERT INTO testTBLB VALUES ( 'apple', 5, 16);

如果其他结果为空,有什么方法可以得到一些结果?

--say code inparam is 16
select fruit, asize, product, quantity  from 
(select product, quantity from testTBLA where code=16),
(select fruit, asize from testTBLB where code=16)

FRUIT      ASIZE                  PRODUCT    QUANTITY               
---------- ---------------------- ---------- ---------------------- 
apple      5                      can        17                    

--say code inparam is 3
select fruit, asize, product, quantity  from 
(select product, quantity from testTBLA where code=3),
(select fruit, asize from testTBLB where code=3)

FRUIT      ASIZE                  PRODUCT    QUANTITY               
---------- ---------------------- ---------- ---------------------- 

0 rows selected

【问题讨论】:

  • 您在这里所做的是INNER JOIN(在您的情况下是笛卡尔)。您可能想尝试使用 OUTER 连接(如果这符合您的要求)。

标签: sql oracle subquery


【解决方案1】:

假设任何一方都可能丢失

SQL> ed
Wrote file afiedt.buf

  1  select fruit, asize, product, quantity
  2    from testTBLA a
  3         full outer join testTBLB b on( a.code = b.code )
  4*  where coalesce(a.code,b.code) = 3
SQL> /

FRUIT           ASIZE PRODUCT      QUANTITY
---------- ---------- ---------- ----------
                      bottle             10

SQL> ed
Wrote file afiedt.buf

  1  select fruit, asize, product, quantity
  2    from testTBLA a
  3         full outer join testTBLB b on( a.code = b.code )
  4*  where coalesce(a.code,b.code) = 16
SQL> /

FRUIT           ASIZE PRODUCT      QUANTITY
---------- ---------- ---------- ----------
apple               5 can                17

【讨论】:

    【解决方案2】:
    select 
      fruit, asize, product, quantity
    from 
      testTBLA
      full join testTBLB using(code)
    where
      code = 16
    

    fiddle

    【讨论】:

      【解决方案3】:

      你的问题不太清楚。

      看看以下方法是否适合你:

      select fruit, asize, product, quantity  from 
      (select product, quantity from testTBLA where code=3) FULL OUTER JOIN
      (select fruit, asize from testTBLB where code=3) ON 1=1
      

      这里是你的数据和我的代码的 SQL Fiddle:http://sqlfiddle.com/#!4/8b70a/2

      【讨论】:

        猜你喜欢
        • 2012-02-23
        • 1970-01-01
        • 1970-01-01
        • 2012-07-09
        • 2021-09-13
        • 1970-01-01
        • 1970-01-01
        • 2021-03-03
        • 1970-01-01
        相关资源
        最近更新 更多