首页 > 解决方案 > 从具有超集值的表中排除子集

问题描述

表 1 有员工 ID 和代码,其中每个员工都有超集代码和子代码。

+-------------+------+
| Employee ID | Code |
+-------------+------+
|         111 |   18 |
|         111 |   19 |
|         111 |   20 |
|         111 |   21 |
|         222 |   40 |
|         222 |   41 |
|         222 |   42 |
+-------------+------+

表 2 有超集码和子集码。

+---------------+-------------+
| Superset code | Subset code |
+---------------+-------------+
|            18 |          19 |
|            18 |          20 |
|            18 |          21 |
|            40 |          41 |
|            40 |          42 |
+---------------+-------------+

我想要仅包含员工 ID 和超集代码的输出。预期结果表:

+-------------+------+
| Employee ID | Code |
+-------------+------+
|         111 |   18 |
|         222 |   40 |
+-------------+------+

如何使用 sql 查询导出此输出?

标签: sqlsql-server

解决方案


我想你想要exists

select t1.*
from table1 t1
where exists (select 1 from table2 t2 where t2.supersetcode = t1.code);

出于性能考虑,您需要在table2(supersetcode).


推荐阅读