sql - SQL 语句选择具有特定值的列
问题描述
我需要一些帮助来编写 sql 语句;我真的不知道如何接近这种情况。我有两个表,Departments 和 Employees,我想从中选择Dpt_num和Dpt_name的部门,这些部门至少有一名员工并且他们的所有员工都来自巴塞罗那
情况1
== Departments =======
| Dpt_num | Dpt_name |
| 1 | A |
| 2 | B |
== Employees ===================
| E_num | Dpt_num | City |
| 1 | 1 | Barcelona |
| 2 | 1 | Barcelona |
这种情况下的结果应该是
Dpt_num Dpt_name
------------------
1 A
案例2
== Departments =======
| Dpt_num | Dpt_name |
| 1 | A |
| 2 | B |
== Employees ==================
| E_num | Dpt_num | City |
| 1 | 1 | Barcelona |
| 2 | 1 | Madrid |
这种情况下的结果应该是空的。
例如,我尝试了这个,但它似乎效率很低,并且在所有情况下都不起作用
select
num_dpt, nom_dpt
from
departements
where
1 = (select count(distinct e.ciutat_empl)
from empleats e
where e.num_dpt = num_dpt)
and not exists (select * from empleats e
where e.ciutat_empl != 'BARCELONA' and e.num_dpt = num_dpt);
我真的很感激任何帮助。谢谢!
解决方案
您想在where
子句中进行过滤。然后,使用exists
and not exists
:
select d.num_dpt, d.nom_dpt
from departaments d
where exists (select 1
from empleats e
where e.num_dpt = d.num_dpt and e.ciutat_empl = 'BARCELONA'
) and
not exists (select 1
from empleats e
where e.num_dpt = d.num_dpt and e.ciutat_empl <> 'BARCELONA'
);
第一个条件检查至少有一名员工来自巴塞罗那。第二个检查没有员工来自任何其他城市。
您的版本中的一个主要问题是您的相关条款:
e.num_dpt = num_dpt
你认为这是在做:
e.num_dpt = departaments.num_dpt
但它确实在做:
e.num_dpt = e.num_dpt
始终限定您的列名。当您在查询中有多个表引用时,这一点尤其重要。
推荐阅读
- symfony - Symfony 5:如何在验证器中获取 isVerified 用户
- python - 如何在 wav 文件中可视化组合信号
- python - AttributeError:“字节”对象没有属性“告诉”
- xslt - XSLT - 拆分节点和组项目
- css - css水平滚动不考虑新的宽度后缩放
- javascript - 承诺后尝试访问数据
- memory - 为什么页面局部性会提高二级缓存命中率?
- javascript - msal.js 与移动浏览器有关
- android - Firebase:如何检查用户身份验证是否被另一个提供商覆盖?
- vba - VBA IsMissing 函数如何在幕后工作?