2011-10-13 63 views
-1
select 
    b.entry_id, 
    b.assign_id, 
    a.profile_type, 
    a.profile_id, 
    a.profile_name, 
    a.profile_status, 
    b.entry_type, 
    b.assign_id, 
    c.chapter_name, 
    d.section_name, 
    h.group_name, 
    i.programme_name, 
    k.subjectprogramme_name, 
    j.masterprogramme_name, 
    l.developmentprogramme_name 
from profile_master a 
left join profile_assign b on (a.profile_id = b.profile_id) 
left join chapter_master c 
     on (b.entry_id = c.chapter_id and b.entry_type='chapter') 
left join section_master d 
     on (b.entry_id = d.section_id and b.entry_type='section') 
left join group_master h 
     on (b.entry_id = h.group_id and b.entry_type='Group' 
      and h.year_id='".$this->year."') 
left join programme_master i 
     on (b.entry_id = i.programme_id and b.entry_type='Programme' 
      and i.year_id='".$this->year."') 
left join subjectprogramme_master k 
     on (b.entry_id = k.subjectprogramme_id and b.entry_type='subjectProgramme' 
      and k.year_id='".$this->year."') 
left join masterprogramme_master j 
     on (b.entry_id = j.masterprogramme_id and b.entry_type='masterProgramme' 
      and j.year_id='".$this->year."') 
left join developmentprogramme_master l 
     on (b.entry_id = l.developmentprogramme_id 
      and b.entry_type='developmentProgramme') 
+1

你真的需要所有這些外部連接?通常,當連接條件不匹配時,您很少需要數據。 – 0xCAFEBABE

+0

如果我在profile_id上​​爲profile_assign表創建索引spped增加了,這是正確的方法 – user993516

回答

0

1)擺脫左連接的地方編碼。使用WHERE過濾

2)我想UNION或7個查詢(由separetely每個實體)子句會在你的情況

0

這是一個很難的問題,而不必直接訪問數據庫來回答更好,所以我會嘗試一個普遍的答案!

  • 對此查詢使用「explain」來查看MySQL是否建議了一些索引。毫無疑問,它會提出幾個問題,因爲你訪問了幾個列,並且通常時間索引將會提高,即使是最慢的也是如此。OUTER JOIN
  • 您對$this->year使用了很多檢查,所以這會建議一些組合索引例如在programme_id 的year_id都在同一個索引

當然,也有可能取決於你如何使用輸出例如溶液,:

  • 如果該查詢運行頻繁地足以成爲用戶等待它的問題,但是對於延遲不是一個問題(例如,可以根據昨晚的數據運行它是可以的),您可以在一夜之間運行它並緩存結果。
0

你真的只當條件通過時,我建議做子查詢,像這樣做的聯接:

SELECT 
    b.entry_id, 
    b.assign_id, 
    a.profile_type, 
    a.profile_id, 
    a.profile_name, 
    a.profile_status, 
    b.entry_type, 
    b.assign_id, 
    CASE b.entry_type 
    WHEN 'chapter' THEN SELECT(c.chapter_name FROM c WHERE b.entry_id = c.chapter_id) 
    WHEN 'section' THEN SELECT(d.section_name FROM d WHERE b.entry_id = d.section_id) 
    WHEN .... 
    END as name 
from profile_master a 
left join profile_assign b on (a.profile_id = b.profile_id) 

如果硬要具有輸出是一樣的,那麼你需要用這個選擇在外部選擇像這樣:

SELECT 
    entry_id, assign_id, ...... 
    , CASE entry_type WHEN 'chapter' THEN name ELSE null END as chapter_name 
    , CASE entry_type WHEN 'section' THEN name ELSE null END as section_name 
FROM 
    (select statement like above) sub