2012-06-27 99 views
0

我有一個SQL Server查詢:優化一個SQL Server查詢

(
    SELECT k12_dms_contacts_institution_jobtitles.job_title_id AS id 
    FROM k12_dms_contacts_institution_jobtitles 
      INNER JOIN k12_dms_institution_master ON k12_dms_institution_master.id = k12_dms_contacts_institution_jobtitles.inst_id 
    WHERE (
       k12_dms_institution_master.state_id='63' 
       AND k12_dms_contacts_institution_jobtitles.glevel_id='1' 
      ) 
    GROUP BY 
      k12_dms_contacts_institution_jobtitles.job_title_id 
) 
INTERSECT 
(
    SELECT k12_dms_contacts_institution_jobtitles.job_title_id AS id 
    FROM k12_dms_contacts_institution_jobtitles 
      INNER JOIN k12_dms_institution_master ON k12_dms_institution_master.id = k12_dms_contacts_institution_jobtitles.inst_id 
    WHERE (
       k12_dms_institution_master.state_id='63' 
       AND k12_dms_contacts_institution_jobtitles.glevel_id='2' 
      ) 
    GROUP BY 
      k12_dms_contacts_institution_jobtitles.job_title_id 
) 
INTERSECT 
(
    SELECT k12_dms_contacts_institution_jobtitles.job_title_id AS id 
    FROM k12_dms_contacts_institution_jobtitles 
      INNER JOIN k12_dms_institution_master ON k12_dms_institution_master.id = k12_dms_contacts_institution_jobtitles.inst_id 
    WHERE (
       k12_dms_institution_master.state_id='63' 
       AND k12_dms_contacts_institution_jobtitles.glevel_id='3' 
      ) 
    GROUP BY 
      k12_dms_contacts_institution_jobtitles.job_title_id 
) 
INTERSECT 
(
    SELECT k12_dms_contacts_institution_jobtitles.job_title_id AS id 
    FROM k12_dms_contacts_institution_jobtitles 
      INNER JOIN k12_dms_institution_master ON k12_dms_institution_master.id = k12_dms_contacts_institution_jobtitles.inst_id 
    WHERE (
       k12_dms_institution_master.state_id='63' 
       AND k12_dms_contacts_institution_jobtitles.glevel_id='4' 
      ) 
    GROUP BY 
      k12_dms_contacts_institution_jobtitles.job_title_id 
) 

有什麼辦法來優化上述query.Intersection只需要在哪裏clause.I想獲取所有的 的基礎上,所有職等都通用的職位。

回答

1

可以使查詢更加簡潔如下:

SELECT IJT.job_title_id AS id 
FROM k12_dms_contacts_institution_jobtitles AS IJT 
INNER JOIN k12_dms_institution_master AS IM 
ON IM.id = IJT.inst_id 
WHERE IM.state_id='63' 
AND IJT.glevel_id IN ('1', '2', '3', '4') 
GROUP BY IJT.job_title_id 
HAVING COUNT(DISTINCT IJT.glevel_id) = 4 
0

這是你在找什麼。 (未經測試)

SELECT k12_dms_contacts_institution_jobtitles.job_title_id AS id 
    FROM k12_dms_contacts_institution_jobtitles 
      INNER JOIN k12_dms_institution_master ON k12_dms_institution_master.id = k12_dms_contacts_institution_jobtitles.inst_id 
    WHERE (
       k12_dms_institution_master.state_id='63' 
       AND (select count(disctinct k12_dms_contacts_institution_jobtitles.glevel_id) from k12_dms_contacts_institution_jobtitles where k12_dms_contacts_institution_jobtitles.glevel_id in ('1','2','3','4')) = 4 
      ) 
    GROUP BY 
      k12_dms_contacts_institution_jobtitles.job_title_id 
+0

不,我只是想取得所有職系通用的職稱。 – user1163513