【问题标题】:ORA-01427: single-row subquery returns more than one row error | But I want multiple valuesORA-01427: 单行子查询返回多行错误 |但我想要多个值
【发布时间】:2020-02-27 00:01:41
【问题描述】:

我有下面的查询,我正在使用返回的子查询创建该查询

ORA-01427:单行子查询返回多于一行的错误。

但我想要子查询返回的所有值,并且连接条件没有其他列。以下是我的示例查询。

select name, 
       dob, 
       cdate, 
      (select value 
         from item a, 
              books b 
        where a.id = b.id 
          and a.newid = b.newid 
          and a.id = s.id 
          and a.bid = s.cid
          and a.eventid=1) col_value,
      (select value2
         from item a, 
              books b 
        where a.id = b.id 
          and a.newid = b.newid 
          and a.id = s.id 
          and a.bid = s.cid
          and a.eventid=1) col_value2
  from sample s, 
       purchase p
 where s.id = p.id
   and s.cid = p.cid

期望的输出

我需要申请分组依据吗?请告诉我您的建议。

【问题讨论】:

  • LEFT JOIN 改为子查询。
  • 今日提示:始终使用现代、明确的JOIN 语法。更容易编写(没有错误),更容易阅读和维护,如果需要更容易转换为外连接!
  • 请使用现代 JOIN 语法,自 SQL-92 起可用,即 28 年前。
  • 那么,如果你有三个值,你想要哪一个?最小值、最大值、平均值、总和?
  • 你说你“想要所有的价值观”。我认为这意味着您需要使用listagg

标签: sql oracle


【解决方案1】:

没有数据有点困难,但是试试:

select name -- please use table alias so you know which table the value is from (s, p or cv)
       , dob
       , cdate
       , cv.value
from sample s 
left join purchase p on s.id=p.id and s.cid=p.cid --or just join
left join (select value, a.id, a.bid  --or just join
           from item a
           left join books b  --or just join
           on a.id=b.id and a.newid=b.newid) cv
on cv.id = s.id and cv.bid = s.cid           
left join (select value2
           from item a 
           left join books b 
           on a.id = b.id and a.newid = b.newid) cv2
on cv2.id = s.id and cv2.bid = s.cid
where cv2.eventid=1;

【讨论】:

  • 谢谢,我更新了我的查询并在我的选择子句中添加了一个子查询,还更新了所需的输出。我相信,现在你会更清楚。
  • 嗨@steve,不客气。我仍然坚持我的回答。你试过了吗?请理解,我们需要从一开始(来自表格)的演示数据和这个“预期结果”数据来更好地理解。另外请解释一下:“连接条件没有其他列”
  • 我正在解释我想要的输出:示例表正在返回:姓名和出生日期。采购表正在返回:Cdate。我必须从 Items Table 中带来 value,value2 列,但由于条件(“where a.eventid=1”),我无法直接连接 Items、Books 和 Sample。如果我在 Where 中应用此条件在子查询之外,它会过滤记录并仅显示 3 个中的 2 个,但我希望所有三个记录都出现。请再次参考查询。
  • 我已经更新了我的答案,但正如我之前所说的解决系统是一样的。抱歉,如果需要更多帮助,您需要从头开始添加数据,而不仅仅是预期的结果数据。
【解决方案2】:
select name, 
       dob, 
       cdate, 
      (select value 
         from  
              books b 
        where a.id = b.id 
          and a.newid = b.newid ) col_value,
      (select value2
         from 
              books b 
        where a.id = b.id 
          and a.newid = b.newid ) col_value2
  from sample s, 
       purchase p,item a
 where s.id = p.id
   and s.cid = p.cid
   and a.id(+)=s.id
   and a.bid(+)=s.cid
   and a.eventid(+)=1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-24
    • 1970-01-01
    • 2022-01-08
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多