我有以下MANY_2_MANY表users_categories
:
user_id | category_id
----------------------
1 | 138
1 | 1262
2 | 1262
3 | 1262
对于具有两个记录的用户,我需要删除所有带有category_id = 1262
的记录-category_id = 138 and 1262
因此,在上述示例中,它必须删除以下记录:
1 | 1262
结果,执行查询后,该表必须如下所示:
user_id | category_id
----------------------
1 | 138
2 | 1262
3 | 1262
答案 0 :(得分:1)
DELETE FROM users_categories
WHERE category_id=1262
AND user_id IN
(SELECT user_id
FROM users_categories
WHERE category_id in (138,1262)
GROUP BY user_id
HAVING count(DISTINCT category_id) =2)
答案 1 :(得分:1)
使用exists
:
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
);