首页 > 解决方案 > SQL 语句选择具有特定值的列

问题描述

我需要一些帮助来编写 sql 语句;我真的不知道如何接近这种情况。我有两个表,Departments 和 Employees,我想从中选择Dpt_numDpt_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);

我真的很感激任何帮助。谢谢!

标签: sqlpostgresql

解决方案


您想在where子句中进行过滤。然后,使用existsand 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

始终限定您的列名。当您在查询中有多个表引用时,这一点尤其重要。


推荐阅读