如何从具有特殊条件的另一个表中删除表中的行?

时间:2018-01-13 01:41:49

标签: sql sql-delete

我开始学习SQL,我坚持这个问题

如果我有这两个表:

行星(名称,大小)

Moon(姓名,PlanetName *)

如何删除超过3个卫星的行星?我不确定我的回答是否正确

DELETE Name
FROM Planet
INNER JOIN Moon WHERE Moon >3

3 个答案:

答案 0 :(得分:3)

你的答案不正确。具有三个以上卫星的行星由下式给出:

select planetname
from moon
group by panetname
having count(*) > 3;

然后,您可以使用inexists

删除行星
delete from planet
    where planetname in (select planetname
                         from moon
                         group by planetname
                         having count(*) > 3
                        );

答案 1 :(得分:1)

delete from planets where 
    (select count(*) from moon where moon.planetname = planet.name) > 3

delete from planets where 
    exists(select count(*) from moon 
           where moon.planetname = planet.name 
           group by planetname  -- you may not need that, because for each row they are all equal, due to the where condition
           having count(*) > 3
          )

答案 2 :(得分:0)

您的查询错误!因为你的查询没有提到计数。

尝试此查询

DELETE from planets
     WHERE
       Name = ((SELECT   COUNT(*)  
                FROM     moon 
                WHERE    moon.planetname = planet.name) > 3 )