2017-04-24 35 views
0

我想減少我的SQL請求的處理時間(實際上它運行10分鐘...) 我認爲問題來自嵌套的SQL查詢。 (對不起,我的英語,我是法國學生)SQL請求太長...如何簡化?

SELECT DISTINCT `gst.codeAP21`, `gst.email`, `gst.date`, `go.amount` 
FROM globe_statistique 
JOIN globe_customers ON `gst.codeAP21`=`gc.codeAP21` 
JOIN globe_orders ON `gc.ID`=`go.FK_ID_customers` 
WHERE `gst.page` = 'send_order' 
AND `gst.date` = FROM_UNIXTIME(`go.date`,'%%Y-%%m-%%d') 

UNION 

SELECT DISTINCT `gst.codeAP21`, `gst.email`, `gst.date`, '-' 
FROM globe_statistique 
WHERE `gst.page` NOT LIKE 'send_order' " 
AND (`gst.codeAP21`,`gst.date`) NOT IN 
      (SELECT `gst.codeAP21`,`gst.date` FROM globe_statistique 
       WHERE `gst.page`='send_order'); 

感謝

+0

重新寫NOT IN的LEFT JOIN。並從不喜歡的測試切換到!=。 – jarlh

+0

我試圖改變不喜歡!=但它是一樣的,但我刪除嵌套的查詢和它的工作,所以問題來自休息的查詢... 我的表globe_statistique:56000行 – Gabi

+0

你的意思是,第一個SELECT是慢的嗎? – jarlh

回答

0

試試這個:

SELECT DISTINCT `gst.codeAP21`, `gst.email`, `gst.date`, `go.amount` 
FROM globe_statistique 
JOIN globe_customers ON `gst.codeAP21`=`gc.codeAP21` 
JOIN globe_orders ON `gc.ID`=`go.FK_ID_customers` 
WHERE `gst.page` = 'send_order' 
AND `gst.date` = FROM_UNIXTIME(`go.date`,'%%Y-%%m-%%d') 

UNION 
SELECT DISTINCT t1.`gst.codeAP21`, t1.`gst.email`, t1.`gst.date`, '-' 
FROM globe_statistique t1 
left join globe_statistique t2 on t1.gst.page =t2.gst.page and t1.gst.date =t2.gst.date and t2.gst.page =send_order 
WHERE `gst.page` <> 'send_order' AND t2.gst.date is null 

但我電子書籍重命名列名並刪除點。

還可以使用EXPLAIN找出原因查詢速度慢,並添加正確的索引

+0

嗨!謝謝你的迴應,但我不明白最後一行,發現 'gst.page' <>'send_order'? – Gabi

+0

@Gabi sould be!= – Jens

+0

它與左連接一起工作,但它已經非常yyyyyyyyyyy .. – Gabi

0

儘量避免使用distinct。爲此,應使用UNION ALL。通過在端基給出了相同的結果:

select codeAP21, email, date, amount 
from (--> your query without distinct but with UNION ALL <--) 
group by codeAP21, email, date, amount 

見:Huge performance difference when using group by vs distinct

+1

已經有一個'UNION',所以這將會做一個隱含的'DISTINCT'太 –

+0

你是對的。你應該也做一個工會。我會編輯我的答案 – frank