左外连接子查询?

时间:2010-08-30 19:34:10

标签: sql oracle plsql ora-01427

----------
User
----------
user_ID(pk)
UserEmail

----------
Project_Account
----------
actno
actname
projno
projname
ProjEmpID
ProjEmpMGRID

其中ProjEmpID,ProjEmpMGRID是user_id,ProjEmpMGRID可以为null。 我需要查找useremail并显示表project_account。我需要使用具有重复值的actNo进行查询。

我的查询是这样的:

 select projno,projname,actno,actname,
(select u.user_email as project_manager from project_account c left outer join users u
     on u.user_id = c.ProjEmpID where actno='some no')as project_manager,

     (select u.user_email as program_manager from project_account c left outer join users u
        on u.user_id = c.ProjEmpMGRID where actno='someno') as program_manager

        from project_account where actno='someno'

我在Oracle中收到的错误消息:

  

ora-01427单行子查询返回   不止一行

当我的子查询返回多个电子邮件ID时,我收到此错误。正如我所说,行为不是不唯一的。我能理解错误,但我无法弄清楚解决方案。我在子查询中执行左外连接,因为在prog manager id中可能存在空值。

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:5)

您得到的错误是您的一个子查询(对于project_manager或program_manager)根据您的条件为您提供了多个ID。这是有道理的,因为多个项目帐户可能具有相同的“actno”,因为您没有将其指定为Primarky Key(pk)

不是使用子查询,而是直接加入用户表以查找ID

 select projno,projname,actno,actname,
  project_user.user_email as project_manager,
  program_user.user_email as program_manager
    from project_account 
    left join User as project_user
      on project_account.ProjEmpID = project_user.user_id
    left join User as program_user
      on project_account.ProjEmpMGRID = program_user.user_id

where actno='someno'

答案 1 :(得分:2)

如下:

select c.projno, c.projname, c.actno, c.actname, u.user_email as project_manager, us.user_email as program_manager

from project_account c

left outer join users u
on u.user_id = c.ProjEmpID

left outer join users us
on us.user_id = c.ProjEmpMGRID

WHERE actno = 'someno'

这样,您就不会运行子查询并返回多个结果并尝试将它们存储为一个值。

答案 2 :(得分:0)

为什么不简单地使用它?

select projno, projname, actno, actname, (select user_email from users where user_id = pa.projempid), (select user_email from users where user_id = pa.projempmgrid) from project_account pa