2

mysql数据库的脚本如下:

Create Table Aircraft
(
    aid integer not null,
    aname nchar(30) not null,
    cruisingrange integer not null,
    primary key (aid)   
);


Create Table Flights
(
    flNo integer not null,
    flFrom nchar(20)not null,
    flTo nchar(20) not null,
    distance integer not null,
    departs time not null,
    arrives time not null,
    price Decimal(6,2) not null,
    primary key(flNo)
);


create table Pilots
(
    pid integer not null,
    pname nchar(20) not null,
    salary Decimal(6,2) not null,
    primary key(pid)
);


create table certified
(
    pid integer not null,
    aid integer not null,
    primary key(pid,aid),
    foreign key(pid) references Pilots(pid)  ON DELETE CASCADE,
    foreign key(aid) references Aircraft(aid) ON DELETE CASCADE
);


INSERT INTO Aircraft(aid,aname,cruisingrange)
VALUES
(1, 'B-450',10000),
(2, 'C-190',4000),
(3, 'RN-110',5000),
(4, 'kp-30',2000),
(5, 'sh-60',1500),
(6, 'mr-70',7000),
(7, 'VK-20',3500);


INSERT INTO Flights(flNo,flFrom,flTo,distance,departs,arrives,price)
VALUES
(100,'city1','city2',1200,'16:00:00','16:30:00',130),
(110,'city3','city4',1000,'18:00:00','19:00:00',160),
(112,'city5','city6',2000,'15:00:00','16:00:00',185),
(115,'city7','city8',4000,'14:00:00','16:00:00',250),
(118,'city9','city3',1500,'18:00:00','19:00:00',220),
(119,'city2','city3',2500,'20:00:00','21:30:00',180);


INSERT INTO Pilots(pid,pname,salary)
VALUES
(400,'jack',150),
(410,'pit',180),
(420,'nami',200),
(430,'rafel',110),
(440,'linda',300);


INSERT INTO Certified(pid,aid)
VALUES 
(400,1),
(400,6),
(410,1),
(420,1),
(420,3),
(420,7),
(440,4),
(440,6);

我想查询所有飞行员认证的薪水超过 187 美元的飞机的名称。事实上,那个“ALL”是我的问题!谁能帮帮我?

4

2 回答 2

4

您可以将问题改写为找到认证飞行员最低工资至少为 187 美元的飞机。

这很容易转换为 SQL:

SELECT aid
FROM ... all your joins here ...
GROUP BY aid
HAVING MIN(salary) >= 187
于 2012-11-09T18:28:30.850 回答
1

我会先对那些拥有您正在寻找的 187 美元的飞行员进行预查询,然后找到他们获得认证的飞机......

select
      QualifiedPilots.*,
      A.AName,
      A.CruisingRange
   from
      ( select 
              P.*
           from
              Pilots P
           where
              P.Salary >= 187 ) as QualifiedPilots
         JOIN Certified C
            on QualifiedPilots.pid = C.pid
            JOIN Aircraft A
               on C.aid = A.aid

由于问题和您对您想要的内容的评论含糊不清,我已经修改为在每个飞行员的基础上包含一个 group_concat。

select
      QualifiedPilots.*,
      group_concat( A.AName ) CertAircraft
   from
      ( select 
              P.*
           from
              Pilots P
           where
              P.Salary >= 187 ) as QualifiedPilots
         JOIN Certified C
            on QualifiedPilots.pid = C.pid
            JOIN Aircraft A
               on C.aid = A.aid
   group by
      QualifiedPilots.pid

此结果仅显示 2 名飞行员……显示飞行员“nami”获得了 3 架飞机的认证,而“linda”获得了 2 架飞机的认证……总共 5 个合格的认证,这是第一个查询返回的……只是名称相同多次,但显示飞机细节。

于 2012-11-09T18:40:35.183 回答