简体   繁体   English

如何在mysql或php中优化或加速我的子查询

[英]How to optimize or speed up my subquery in mysql or in php

Sample query: 查询样例:

 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

Expected Output: 预期产量:

id | name | address | message |

note: assuming table 1 and table 2 have thousands of rows and table 3 has millions of rows 注意:假设表1和表2具有数千行,表3具有数百万行

Is it any faster like this ? 这样更快吗?

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

Here is a modified version of your query 这是查询的修改版本

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;

Now you will need indexes on the tables, and I am assuming ids of all the tables are primary key and are indexed so no need to add additional indexes on them. 现在您将需要在表上建立索引,并且我假设所有表的ID都是主键并已建立索引,因此无需在其上添加其他索引。 The following index would be needed 需要以下索引

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);

NOTE : Make sure to take a table backup before applying the indexes. 注意:确保在应用索引之前进行表备份。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM