SQL 查询以排除已映射到另一个列 ID 的记录并向它们显示其余部分

SQL query to exclude records that already mapped with another column id and show rest to them

我正在努力实现以下但无法实现

Id   CatID  CategoryName
-------------------------
1    1      Movies
2    1      Movies
3    2      Books
4    3      Tools

我想要实现的是:

我要所有记录:

  1. ID 不为 1 且
  2. 排除 ID = 1 与其他 ID 共享的 (CatID) 记录。在这种情况下,Id = 1 和 Id = 2 共享相同的 CATID = 1(电影)。我想删除这些记录并显示其余的记录。

输出:

Id   CatID  CategoryName
-------------------------
3    2      Books
4    3      Tools

您可以使用 not exists:

select t.*
from mytable t
where not exists (
    select 1 from mytable t1 where t1.catID = t.catID and t1.id = 1
)

为了提高此查询的性能,请考虑 (catID, id) 上的索引。