寻找没有员工的商场
有一个名为 users 的表,看起来是这样的:
| mall_id | name | position |
|---|---|---|
| 1 | Max | boss |
| 1 | Dan | employee |
| 1 | Mike | employee |
| 2 | Ben | boss |
| 3 | Susan | boss |
| 3 | Larry | employee |
| 3 | Pat | employee |
每个购物中心(mall)有一个‘boss’以及可能的员工。这些信息都存储在同一个列表中。
现在该如何检查哪个商场没有员工?例如,编号为2 的商场只有一个老板,没有员工。
没有员工的商场应列出mall ID以及该商场老板的姓名。
解决方案
快速但粗糙的查询——在大型表上不推荐使用,但对于几行数据来说完全够用
select mall_id,name
from users
where position='boss'
and mall_id not in (select distinct mall_id from users where position='employee');`
备选方案
我们可以考虑三种查询
- max(position)=min(position)='boss' - 该商场中只有 'boss'。
select mall_id,min(name) name
from users
group by mall_id
having min(position)='boss' and min(position)=max(position);
- 在此商场中不存在position<>'boss' 的用户
select mall_id,name,position
from users t1
where not exists(select 1 from users t2 where t2.mall_id=t1.mall_id and position<>'boss');
- 自连接(anti-join)表 - 取行t1.position='boss'、t1.position<>'boss' 且t2.* 为null
select t1.mall_id,t1.name,t1.position
from users t1
left join users t2 on t1.mall_id=t2.mall_id and t2.position<>'boss'
where t1.position='boss' and t2.mall_id is null;
如果你有索引
create index ix_users_mall_id_position on users(mall_id,position);
对我而言,选项1更可取。 示例
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。