单行子查询返回多行 - 无更新或插入

时间:2013-10-23 06:21:09

标签: sql oracle oracle10g

我写了以下脚本

SELECT vil.account_id , 
       vil.imp_id, 
       vil.owner ,
       vil.start_date,
       CASE  
         WHEN ac.status = 4  
         THEN status_date  
         ELSE NULL  
       END AS Live_date,
       cs.country_code  
  FROM ACCOUNT ac  
  INNER JOIN vu_imp_list vil  
     ON vil.account_id = ac.account_id  
  INNER JOIN entity e  
     ON ac.entity_id = e.entity_id  
  INNER JOIN country_specifics cs  
     ON e.country_id = cs.country_id  
  WHERE (vil.account_id, vil.start_date) =   
        (SELECT vils.account_id, MIN(vils.start_date)   
           FROM vu_imp_list vils  
          WHERE vil.account_id IN  ('825808009','987323136')  
          group by vils.account_id);  

但我一直收到错误

SQL Error: ORA-01427: single-row subquery returns more than one row  
01427. 00000 -  "single-row subquery returns more than one row"  

我尝试将rownum = 1添加到子查询的where子句中,但似乎查询正在永远运行。我已经单独测试了子查询,并为每个account_id返回一行。此处的大多数类似问题都与insertupdate问题有关,而不仅仅是查询。

2 个答案:

答案 0 :(得分:1)

您需要确保子查询正好返回1行(或0)。我想你想要这个:

  WHERE vil.start_date =   
        (SELECT MIN(vils.start_date)   
           FROM vu_imp_list vils  
          WHERE vils.account_id IN ('825808009','987323136')  
        ); 

或如果子查询返回2行或更多行并且您想要将IN与其中任何一行进行比较,请使用start_date

  WHERE vil.start_date IN   
        (SELECT MIN(vils.start_date)   
           FROM vu_imp_list vils  
          WHERE vils.account_id IN ('825808009','987323136')
          GROUP BY vils.account_id 
        ); 

或者也许这样,如果你想要一个相关的子查询:

  WHERE vil.account_id IN ('825808009','987323136')
    AND vil.start_date =   
        (SELECT MIN(vils.start_date)   
           FROM vu_imp_list vils  
          WHERE vils.account_id = vil.account_id 
        ); 

答案 1 :(得分:0)

如果您的表vu_imp_list同时显示825808009 987323136account_id,那么这个内部查询:

(SELECT vils.account_id, MIN(vils.start_date)   
 FROM vu_imp_list vils  
 WHERE vil.account_id IN ('825808009','987323136')  
 group by vils.ob10_account_id)

将生成2行,每行2列。

麻烦的是,您无法在WHERE中执行多列相等检查:

WHERE (vil.account_id, vil.start_date) =   
    (SELECT vils.account_id, MIN(vils.start_date) ... )