删除出现一次的另一个表中的值

时间:2019-02-25 03:12:59

标签: 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    

我试图在第二个表中delete的行movie_id = 2,但前提是相应的rent_id出现一次。例如,我想删除一部电影,如果租金仅基于这部电影,则应该在第二张桌子上删除,但是对于rent_id = 3,我想将其保留在桌子上,因为有与之相关的其他电影。

我尝试过的是:

delete 
from en_aluguel 
where id_aluguel = (select id_aluguel 
                    from re_aluguel_filme 
                    where id_filme = 2 havin count(*) = 1);

但结果不是我想要的

3 个答案:

答案 0 :(得分:1)

您似乎想要:

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"
                    );

答案 1 :(得分:0)

您可以这样做:

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
);

经过rextester

的测试

答案 2 :(得分:0)

您必须先分组再使用。希望这对您有用。

DELETE FROM public.movies
    WHERE movie_id in (select movie_id from movies group by movie_id having count(*) >= 2);