执行计划成本较低的SQL查询

时间:2016-12-13 17:35:08

标签: sql sql-server database

我有这些表和这个查询,我需要使用较低的执行计划成本进行相同的查询。

CREATE TABLE PilotSkills
(pilot CHAR(15) NOT NULL,
 plane CHAR(15) NOT NULL,
 PRIMARY KEY (pilot, plane));

CREATE TABLE Hangar  -- ALWAYS CONTAINS AT LEAST ONE TUPLE
(plane CHAR(15) PRIMARY KEY);

SELECT DISTINCT pilot
  FROM PilotSkills AS PS1
 WHERE NOT EXISTS
       (SELECT *
          FROM Hangar
         WHERE NOT EXISTS
               (SELECT *
                  FROM PilotSkills AS PS2
                 WHERE (PS1.pilot = PS2.pilot)
                   AND (PS2.plane = Hangar.plane)));

1 个答案:

答案 0 :(得分:0)

这样的东西?

rextester:http://rextester.com/ORG70581

create table PilotSkills (
   pilot char(15) not null
 , plane char(15) not null
 , primary key (pilot, plane)
 );
insert into PilotSkills (pilot,plane) values (1,1),(1,2),(1,3),(2,1),(2,2),(3,3)

create table Hangar(plane char(15) primary key);
 insert into Hangar values (1),(2),(3)    

select ps.Pilot
from PilotSkills ps 
  inner join Hangar h on ps.Plane=h.Plane
group by ps.Pilot
having count(distinct ps.Plane)=(select count(distinct i.Plane) from Hangar i)

根据您的实际表格和数据,distinct中可能不需要count