2013-08-02 41 views
0

爲什麼在UNION關鍵字查詢中運行非常慢的mysql?用UNION關鍵字查詢在mysql中運行速度非常慢

我已經使用UNION關鍵字創建了一個查詢,但每次執行它時,顯示輸出都需要很長時間。

這是我使用的查詢。

SELECT process_trained AS Training_Title, 
    org_party AS Organizing_Party, 
    duration AS Duration, 
    Concat(Date_format(sptrain_from, '%d-%b-%y'), " to ", 
    Date_format(sptrain_to, '%d-%b-%y'), "") AS SpecialTraining_Date, 
    trainor AS Trainor, 
    category AS Category, 
    training_type AS Training_Type, 
    train_id, 
    Date_format(cert_date, '%d-%b-%Y') AS Date_Certified, 
    Date_format(re_certdate, '%d-%b-%Y') AS Re_Certificaton, 
    remarks, 
    filename 
FROM(SELECT *, 
       cert_date AS cdate 
     FROM tbldirtraining 
     UNION ALL 
     SELECT *, 
       sptrain_from 
     FROM tbldirtraining) jes 
WHERE emp_id = '6555' 
     AND cdate <> '' 
ORDER BY cdate; 

是否有任何可能的方法可以幫助如何更快地運行此查詢。

在此先感謝。

+0

你能告訴執行計劃? –

+0

'tbldirtraining'中有多少行?另外,你爲什麼要把桌子與自己結合起來? – Sebas

+0

@Sebas ...總而言之,在tbldirtraining中有2053行,正如你所看到的,上面的查詢我使用了WHERE子句來指定查詢顯示的訓練細節。所以身份證號碼6555必須顯示13行,因爲他有13次訓練,但是每次使用UNION或UNION ALL時,結果都是重複的行,所以不是13而是13,它變成了26,這就是爲什麼我把條件'WHERE cdate <>'' '其中cdate是我用於兩個聯合行的ALIAS。我將一個列合併到一個表中,這些列是日期列,並且它們必須同時排序。 –

回答

0

試試這個

 SELECT process_trained AS Training_Title, 
org_party AS Organizing_Party, 
duration AS Duration, 
Concat(Date_format(sptrain_from, '%d-%b-%y'), " to ", 
Date_format(sptrain_to, '%d-%b-%y'), "") AS SpecialTraining_Date, 
trainor AS Trainor, 
category AS Category, 
training_type AS Training_Type, 
train_id, 
Date_format(cert_date, '%d-%b-%Y') AS Date_Certified, 
Date_format(re_certdate, '%d-%b-%Y') AS Re_Certificaton, 
remarks, 
filename 
FROM tbldirtraining 
WHERE emp_id = '6555' 
AND cert_date <> '' 
ORDER BY cert_date desc,sptrain_from asc; 
+0

我已經嘗試過這個查詢,但輸出只按cert_date排序,我想要的是通過cert_date和sptrain_from對它進行排序。就像這樣 - 當cert_date是2011-01-25,2011-02-01,sptrain_from是2011-01-22,2013-08-02時,輸出必須按如下排序:2011-01-22, 2011-01-25,2011-02-01,2013-08-02。 –

+0

我沒有幫助,如果你添加'sptrain_from'命令由我編輯? –

+0

ahm。其實先生不是,因爲我已經嘗試過那個,結果不是我期待的那個。但無論如何,感謝您提供的幫助:先生:-) –