Sql 删除另一个出现一次的表中的值
我有以下表格:Sql 删除另一个出现一次的表中的值,sql,postgresql,Sql,Postgresql,我有以下表格: movie_id rent_id 1 1 2 2 2 3 3 3 3 4 3 5 rent_id client_id 1 1 2 1 3 2 4 4 5 4 我试图删除第二个表中电影id=2的行,但前提是相应的租金id出现
movie_id rent_id
1 1
2 2
2 3
3 3
3 4
3 5
rent_id client_id
1 1
2 1
3 2
4 4
5 4
我试图删除第二个表中电影id=2
的行,但前提是相应的租金id
出现一次。例如,我想删除一部电影,如果租金仅基于这部电影,它应该在第二个表中删除,但在租金_id=3
的情况下,我希望将其保留在表中,因为还有其他与之相关联的电影
我尝试的是:
delete
from en_aluguel
where id_aluguel = (select id_aluguel
from re_aluguel_filme
where id_filme = 2 havin count(*) = 1);
但结果并不是我想要的你可以这样做:
DELETE FROM en_aluguel e
WHERE EXISTS (
SELECT 1
FROM (
SELECT movie_id, rent_id,
COUNT(*) OVER (PARTITION BY rent_id) AS cnt
FROM re_aluguel_filme
) r
WHERE r.rent_id = e.rent_id
AND r.movie_id = 2
AND r.cnt = 1
);
在中测试您必须有一个组才能使用having。希望这对你有用
DELETE FROM public.movies
WHERE movie_id in (select movie_id
from movies
group by movie_id
having count(*) >= 2);
你似乎想要:
delete from en_aluguel
where id_aluguel in (select id_aluguel
from re_aluguel_filme
group by id_aluguel
having count(*) = 1 and -- only one filrm
min(id_filme) = 2 -- and that is film "2"
);
那么你的预期结果是什么?