在两个表中使用子选择优化查询

Optimizing query with subselect in two tables

Table employee 有两列:

Table external_job 也有两列:

我得找一个拿到最高薪水的人。 结果必须有三列和一行:

我进行了查询,但客户要求我不要使用子select查询。

遇到这种情况我该怎么办?

我的查询是:

select *
  from (select a.id,
               a.name,
               (select sum(salary)
                  from external_job b
                 where b.id = a.id) salary
          from employee a
         order by salary desc)
 where rownum = 1

假设ID是两边的主键。

 select  ID, NAME, SALARY from employee e ,  external_job a where e.id= a.id 
 order by salary desc
 limit 1

使用 order by 和一些方法将结果限制为一行。在标准 SQL 中是:

select ej.id, e.name, ej.salary
from employee e join
     external_job ej
     on ej.id = e.id
order by ej.salary
fetch first 1 row only;

并非所有数据库都支持 fetch first。有些使用 limitselect top 甚至更神秘的结构。