什么是正确的SQL查询

时间:2012-11-09 18:24:46

标签: mysql sql

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美元。事实上,“所有”是我的问题!有人可以帮助我吗?

2 个答案:

答案 0 :(得分:4)

你可以将这个问题重新解释为找到飞行员,其认证飞行员的最低工资至少为187美元。

转换为SQL很简单:

SELECT aid
FROM ... all your joins here ...
GROUP BY aid
HAVING MIN(salary) >= 187

答案 1 :(得分: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个合格认证,这是第一个查询返回的...同名多次,但显示了飞机的细节。