SQL(Oracle)嵌套的选择参数

时间:2013-06-14 13:24:39

标签: sql oracle select nested

我正在尝试做类似的事情:

select fred.name
  , fred.emp_num
from fred
  , joe
  , (select * from
      (select yr_bonus
        , 1 grade
      from mark 
      where mark.department = fred.department)
      union
      (select
        0 yr_bonus
        , 2 grade
      from dual)
    ) pay
where fred.division = joe.division
and fred.grade = pay.grade;

这不起作用。我似乎无法弄清楚如何将mark.department绑定到fred.department,从2级深处选择。我该如何做到这一点?

2 个答案:

答案 0 :(得分:2)

因为在FROM子句中您无法访问另一个表,所以必须在where子句中使用JOINS或连接表。此外,您的查询似乎不正确,描述您想要做什么?

如果我理解正确,您的查询可以像这样重写:

select fred.name
  , fred.emp_num
from fred
  , joe
where fred.division = joe.division
and ((fred.grade = 1 and fred.department in (select department from mark) 
or (fred.grade = 2))

答案 1 :(得分:1)

SELECT  fred.name
,       fred.emp_num
FROM    fred
JOIN    joe
ON      fred.division = joe.division
JOIN
(
        SELECT  *
        FROM
        (
            SELECT  yr_bonus
            ,       1 grade
            FROM    mark
            UNION
            SELECT  0 yr_bonus
            ,       2 grade
            FROM    dual
        ) mark
        JOIN    fred
        ON      mark.department = fred.department
) pay
ON      fred.grade = pay.grade;