SQL同表联接查询实现同城市多任职经历的人员配对检索
SQL查询问题求助
在SQL开发过程中遇到无法独立解决的查询逻辑问题,已准备好包含完整测试数据的数据库复现脚本,需要对应的实现思路与方法指导。
核心查询目标
需要输出满足规则的人员配对结果:
- 配对组合内的每一名成员,都具备在同一城市累计任职2家及以上公司的经历
- 参考规则下的典型配对关系:
- Eric与Lisa:两人均有Denver地区2家公司的任职经历
- Wendy与同城市符合条件的配对人员:两人均有Seattle地区2家公司的任职经历(原需求描述中提到的“Ben”为笔误,对应测试数据中的匹配人员为Sam)
可复现的测试脚本
以下代码可直接运行,搭建完整的问题测试环境:
create database TestDatabase use TestDatabase create table Person ( person_id int not null primary key, perons_name varchar(20) not null ); create table City ( city_id int not null primary key, city_name varchar(20) not null ); create table Company ( company_id int not null primary key, company_name varchar(20) not null, located_in int null foreign key(located_in) references City(city_id) ); create table worked_at ( person_id int not null, company_id int not null, foreign key(person_id) references Person(person_id), foreign key(company_id) references Company(company_id) ); insert into City(city_id, city_name) values (1, 'Denver'), (2, 'Colorado'), (3, 'Seattle'); insert into Company(company_id, company_name, located_in) values (1, 'Achme', null), (2, 'Local Store', 1), (3, 'The Bizz', 1), (4, 'Drinks', 3), (5, 'Foodie', 3); insert into Person(person_id, perons_name) values (1, 'Eric'), (2, 'Sam'), (3, 'Wendy'), (4, 'Lisa'), (5, 'John'); insert into worked_at(person_id, company_id) values (1, 1), (1, 2), (1, 3), (4, 2), (4, 3), (4, 1), (3, 2), (5, 1), (3, 4), (3, 5), (2, 4), (2, 5);
当前实现卡点
此前尝试编写逻辑筛选“在同一城市任职至少2家公司”的人员,但始终无法得到正确的筛选结果,也不清楚如何进一步基于筛选结果生成符合要求的人员配对,需要对应的技术指导。
内容的提问来源于stack exchange,提问作者SecretIndividual
相关产品推荐
相关产品推荐

