【问题标题】:SQL DML Exercise 14SQL DML 练习 14
【发布时间】:2014-11-01 21:35:38
【问题描述】:

我遇到了一个问题,我不知道如何获得正确的查询。所以首先,这个问题是参考 www.sql-ex.ru 及其 DML 部分中的练习 10。

这是所有信息:

简短的数据库描述“船舶”:

参与二战的海军舰艇数据库正在考虑中。数据库有以下关系:

Classes(class, type, country, numGuns, bore, displacement) 
Ships(name, class, launched) 
Battles(name, date) 
Outcomes(ship, battle, result) 

类中的船舶被安排到一个项目中。一个类通常被分配给所考虑的类中的第一艘船的名称(头船);否则,类名与数据库中的任何船名不一致。 等级关系包括等级名称、类型(bb 代表战舰,或 bc 代表战列巡洋舰)、建造国家、主炮数量、炮口径(炮管直径,以英寸为单位)和排量(重量,吨)。 Ships 关系包括船名、船级名和发射年份。战斗关系包括舰艇参加的战斗的名称和日期;而他们参与战斗的结果(沉没、受损或安然无恙 - OK)在结果关系中。 注: 1) 结果关系可能包括未包括在船舶关系中的船舶。 2) 沉船之后就不能参加战斗了。

这是练习和提示:

  • 删除数据库中少于三艘船的类别(考虑到结果表)。*

任务 #14 的提示

  1. 数据库中没有船只的类也对应于任务的术语,例如0
  2. 检查一个类在 Ships 表中有 2 艘普通船,在 Outcomes 表中有头船的情况,即该类在 DB 中有 3 艘船。

这是我的查询:

delete from classes
where class not in (

select distinct c.class from classes c, ships s
where c.class = s.class
group by c.class
having count(name) >= 3
union
select distinct c.class from classes c, outcomes o
where c.class = o.ship
group by c.class
having count(ship) >= 3
union
select distinct s.class from ships s, outcomes o
where s.class = o.ship 
group by s.class
having count(name) >= 3)

【问题讨论】:

    标签: sql select sql-delete dml


    【解决方案1】:

    sql-ex dml ex 14

    delete
    from classes
    where class in (
    select c.class
    from classes c
    left join (
    select name,class from ships -- classes from Ships
    union
    select ship,ship from outcomes -- lead classes from Outcomes
    ) so on c.class=so.class
    group by c.class
    having count(*)<3
    )
    

    【讨论】:

      【解决方案2】:
      DELETE FROM classes 
      WHERE  class IN (SELECT class 
                       FROM   ships 
                       GROUP  BY class 
                       HAVING Count(NAME) < 3); 
      

      【讨论】:

      • 抱歉没看到,我想这有点晚了,但我会在以后解释。第二个请求使用 Count 选择所有少于三艘船的类。然后我们正在寻找我们的类“主键”与少于三艘船的类相同的所有类。然后我们删除匹配的类。 PS:对不起我的英语,希望它有帮助
      【解决方案3】:
      delete from classes 
      where class not in (
      select t.klas
      from
      (select class klas, count(class)no
      from ships 
      group by class
      
      union all
      
      select ship klas, count(ship)no
      from outcomes
      where ship not in (select s1.name from ships s1)
      group by ship) t
      group by t.klas
      having sum(t.no) >= 3)
      

      【讨论】:

        猜你喜欢
        • 2014-03-24
        • 2015-08-18
        • 2015-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多