要获取姓氏:
select lastname
from names n join
position p
on n.id = p.id
where firstname in ('ben', 'rob')
group by lastname
having count(distinct firstname) = 2 and
1+max(case when firstname = 'ben' then p.position end) = max(case when firstname = 'rob' then p.position end)
然后,您可以通过以下方式获取原始列表:
select n.*, p.position
from names n join
position p
on n.id = p.id
where firstname in ('ben', 'rob') and
lastname in (select lastname
from names n join
position p
on n.id = p.id
where firstname in ('ben', 'rob')
group by lastname
having count(distinct firstname) = 2 and
1+max(case when firstname = 'ben' then p.position end) = max(case when firstname = 'rob' then p.position end)
)
我认为以下查询回答了您的问题,但需要注意的是,这会将名称组合成一行:
select nben.*, p.position, nrob.*, prob.position
from names nben join
positions p
on nben.id = p.id and
nben.firstname = 'ben' join
names nrob
on nrob.firstname = 'rob' and
nrob.lastname = nben.lastname join
positions prob
on nrob.id = prob.id and
p.position = prob.position - 1
此外,这是未经测试的。