首页 > 解决方案 > 如何将一个表的每一组与另一个表中的列进行比较?

问题描述

我有两张桌子:

类型表

TypeId      PersonClassificationId
----------------------

 1           1  
 1           2 
 1           3 
 2           1 
 2           2 

人员分类表

PersonClassificationId Capacity
----------------------

 1                        2  
 2                        2 
 3                        2           

我需要选择在整个 TypeTable 表中没有在 PersonTable 中指定的至少一个 PersonClassificationID 的TypeId

所以,如果 PersonTable 有 1、2、3,那么应该选择 TypeId = 2,因为TypeTable 中没有记录

TypeId      PersonClassificationId
----------------------

 2           3  

我怎样才能做到这一点?不希望使用游标:)

标签: sqlsql-servertsql

解决方案


我认为你可以通过生成所有可能的类型和分类组合来做你想做的事,然后过滤映射表中不存在的那些:

select t.TypeId, pc.PersonClassificationId
from (select distinct TypeId from TypeTable) t
cross join PersonClassificationTable p
where not exists (
    select 1 
    from TypeTable t1 
    where t1.TypeId = t.TypeId and t1.PersonClassificationId = p.PersonClassificationId
)

推荐阅读