Sql 为在同一表中有另一条记录的用户从表中删除记录
我有以下多个表Sql 为在同一表中有另一条记录的用户从表中删除记录,sql,postgresql,Sql,Postgresql,我有以下多个表用户类别: user_id | category_id ---------------------- 1 | 138 1 | 1262 2 | 1262 3 | 1262 我需要删除同时具有记录-category\u id=138和1262的用户的category\u id=1262的所有记录,因此,在上述示例中,它必须删除以下记录: 1 | 1262 因此,执行查询后,表必须如下所示: user_id |
用户类别
:
user_id | category_id
----------------------
1 | 138
1 | 1262
2 | 1262
3 | 1262
我需要删除同时具有记录-category\u id=138和1262的用户的category\u id=1262
的所有记录,因此,在上述示例中,它必须删除以下记录:
1 | 1262
因此,执行查询后,表必须如下所示:
user_id | category_id
----------------------
1 | 138
2 | 1262
3 | 1262
使用存在
:
delete from user_categories uc
where category_id = 1262 and
exists (select 1
from user_categories uc2
where uc2.user_id = u.user_id and uc2.category_id = 138
);
使用存在
:
delete from user_categories uc
where category_id = 1262 and
exists (select 1
from user_categories uc2
where uc2.user_id = u.user_id and uc2.category_id = 138
);