gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:06:00 29 4
gpt4 key购买 nike

我正在尝试将此子查询重写为连接。我已经阅读了关于 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com