mysql - 如何将数据库子查询重写为连接?

标签 mysql sql

我正在尝试将此子查询重写为连接。我已经阅读了关于 SO 的其他问题,但无法解决这个问题。

create table job (
  emplid int, 
  effdt date,
  title varchar(100),
  primary key (emplid, effdt)
);

insert into job set emplid=1, effdt='2010-01-01', title='Programmer';
insert into job set emplid=1, effdt='2011-01-01', title='Programmer I';
insert into job set emplid=1, effdt='2012-01-01', title='Programmer II';

insert into job set emplid=2, effdt='2010-01-01', title='Analyst';
insert into job set emplid=2, effdt='2011-01-01', title='Analyst I';
insert into job set emplid=2, effdt='2012-01-01', title='Analyst II';

#Get each employees current job:
select *
from job a
where a.effdt=
    (select max(b.effdt) 
    from job b
    where b.emplid=a.emplid);

结果:

+--------+------------+---------------+
| emplid | effdt      | title         |
+--------+------------+---------------+
|      1 | 2012-01-01 | Programmer II |
|      2 | 2012-01-01 | Analyst II    |
+--------+------------+---------------+

我想将查询重写为一个没有子查询的连接。这可能吗?

最佳答案

将其写成join 可能有点违反直觉。这个想法是使用 left outer join 并在条件中包含 b.effdt > a.effdt。此条件将匹配行,除非 a.effdt 取最大值。然后查询可以使用 where 过滤这些:

select a.*
from job a left outer join
     job b
     on  b.emplid = a.emplid and
         b.effdt > a.effdt
where b.effdt is NULL;

关于mysql - 如何将数据库子查询重写为连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20670303/

相关文章:

sql - Visual Studio 2010 的 SQL 架构和数据比较 - 可以从代码访问吗?

mysql - SQL 查询中的重复列名

sql - 将 SQL 查询转换为关系代数

mysql - SQL 脚本创建存储过程 - 导入错误

php - 严格标准 : Only variables should be passed

php - MySQL 行数错误

php - 从 MySQL 中按月和年分组的时间戳列中获取记录

c# - SQL Server 2008 中的正则表达式

mysql - SQL 语法错误。存储过程的创建

c# - 尝试将数据插入一行时为什么会出现SQL语法错误?