2015-05-09 49 views
0

樣品查詢加快我的子查詢:如何優化或MySQL或在PHP

SELECT 
    table1.t1_id,table1.name, 
    table2.address, 
    (
     SELECT message 
     FROM table3 
     WHERE logid = table1.t1_id 
       AND message NOT LIKE "[ SYSTEM%" 
     ORDER BY logs 
     DESC LIMIT 1 
    ) as message 
FROM table1 
INNER JOIN table2 
ON table1.t1_id = table2.t2_id 
WHERE table1.dateCreated 
BETWEEN CAST('2015-01-01' as Date) 
     AND CAST('2015-05-30' as Date) 
ORDER BY table1.dateCreated DESC 

預期輸出:

id | name | address | message | 

注:假設表1和表2有幾千行和表3有數百萬行

+0

您的查詢執行多少時間?我的意思是基準。 –

+0

顯示基於phpmyadmin的行0 - 29(總共1,002次,查詢耗時27.2299秒)。 –

+0

你能以創建表的形式發佈一個SQL小提琴或你的數據庫模式,並插入帶有示例數據的語句嗎? –

回答

0

這是您的查詢

select 
t1.t1_id, 
t1.name, 
t2.address, 
t3.message 
from table1 t1 
join table2 t2 on t1.t1_id = t2.t2_id 
join table3 t3 on t3.logid = t1.t1_id 
join(
    select max(logs) as logs,logid from table3 
    where 
    message NOT LIKE "[ SYSTEM%" 
    group by logid 
)x 
on x.logs = t3.logs and x.logid = t3.logid 
where 
t1.dateCreated BETWEEN CAST('2015-01-01' as Date) AND CAST('2015-05-30' as Date) 
ORDER BY t1.dateCreated DESC; 

現在需要對錶的索引的修改版本,我假設所有 表的IDS是主鍵和被索引所以沒必要在它們上添加額外的索引。 以下指數將需要

alter table table3 add index logs_idx(logs); 
alter table table3 add index message_idx(message); 
alter table table3 add index logid_idx(logid); 

alter table table1 add index dateCreated_idx(dateCreated); 

注:確保應用索引之前採取表備份。

+0

嗨。我將在創建必要的索引後運行上面的查詢? –

+0

對不起,我只是一個初學者:) –

+0

是先創建索引,然後再做表的備份。然後運行查詢並查看性能。 –

0

這是否有更快的速度?

SELECT table1.t1_id, table1.name,table2.address, m.message 
FROM 
table3 as m, 
table1 INNER JOIN table2 ON table1.t1_id = table2.t2_id 
WHERE table1.dateCreated 
BETWEEN CAST('2015-01-01' as Date) AND CAST('2015-05-30' as Date) 
and m.logid = table1.t1_id 
and m.message not like "[ SYSTEM%" 
having min(m.log) 
ORDER BY table1.dateCreated DESC 
+0

錯誤:#1111 - 組函數的使用無效 –

+0

你可以發佈一些示例表數據嗎? –

+0

嘗試使用有,將更新答案 –