2017-04-24 31 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