开发者社区> 问答> 正文

Oracle连表查询- oracle报错

Oracle连表查询,A表一条数据,B表有多条数据,连表查询,取A表信息和B表排序后的一条数据,如何在一条SQL里查询?

求教,ORACLE查询的一个疑惑,如题描述:Oracle连表查询,A表一条数据,B表有多条数据,连表查询时,取B表排序后的一条数据,如何在一条SQL里查询?

 

案例:

比如有人员信息表person_info,月收入表person_income,用person_id字段关联

 

person_info表

person_id

姓名NAME

 

person_income表

person_id

月收入income

更新时间updated_date

 

 

我要根据person_id查询 人员姓名和他最近一个月的薪资

 

查询的时候,下面这2个SQL都是正确的,但是结合在一起就报错了,这是为啥......

正确的sql

1、根据person_id查询最新薪资

select income from (select income from person_income where person_id='001' order by updated_date desc) where rownum=1

 

2、根据person_id查询姓名和默认排序的第一条薪资

select A.person_name,(select B.income from person_income B where A.person_id=B.person_id and rownum=1) from person_info A where A.person_id ='001'

 

 

报错的SQL

根据person_id查询姓名和排序后的薪资

select A.person_name,(select income from (select B.income from person_income B where A.person_id=B.person_id order by updated_date desc) where rownum=1) from person_info A where A.person_id ='001'

报错信息:

ORA-00904:"A"."person_id":标识符无效

 

展开
收起
montos 2020-05-30 10:42:56 451 0
1 条回答
写回答
取消 提交回答
  • A在括号外定义,在括号内使用当然会报错。

    另外,排序要放到最外层。

    ######

    select *
      from (select p.person_id, p.name, pd.income, pd.updated_date
              from person_info p
              left join person_income pd
                on p.person_id = pd.person_id
             where p.person_id = #personId#
             order by pd.updated_date)
     where rownum = 1
     

    2020-05-30 10:43:07
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
PostgresChina2018_樊文凯_ORACLE数据库和应用异构迁移最佳实践 立即下载
PostgresChina2018_王帅_从Oracle到PostgreSQL的数据迁移 立即下载
Oracle云上最佳实践 立即下载