Rumah > Artikel > pangkalan data > mysql-MySQL两个表关联查询慢
mysql
有A,B两个表,
A表是所有客户端的日志,数量在两百万
B表是客户端明细,数量在两万
现在需要筛选出符合某些条件的客户端的日志,SQL如下:
<code>SELECT A.*FROM `VIEW_DATA.basic_LOG.20160523` AINNER JOIN (SELECT AGT_ID FROM VIEW_AGENT where AGT_GRP_ID in (999)) B ON A.`BAS_AGT_ID` = B.AGT_IDORDER BY `BAS_TIME` DESC, `ID` DESC LIMIT 7;</code>
1 SIMPLE basic_log index IX_BASIC_LOG_BAS_AGT_ID IX_BASIC_LOG_BAS_TIME_ID 10 7 100 Using where
1 SIMPLE a eq_ref PRIMARY PRIMARY 4 ocular3_data.20160523.basic_log.BAS_AGT_ID 1 100
1 SIMPLE b eq_ref PRIMARY PRIMARY 4 ocular3.a.AGT_GRP_ID 1 100 Using where; Using index
1.将AGT_GRP_ID in (999)改为AGT_GRP_ID in =999;
2.在需要的字段建索引
参考自:
MySQL如何优化嵌套Join http://www.data.5helpyou.com/article272.html
两张表反过来写,然后把内链接改为外链接,将AGT_GRP_ID in (999)改为AGT_GRP_ID in =999;
SELECT A.*,B.AGT_ID
FROM VIEW_DATA.basic_LOG.20160523 A ,VIEW_AGENT B where B.AGT_GRP_ID=999 and A.BAS_AGT_ID = B.AGT_ID
ORDER BY A.BAS_TIME DESC, A.ID DESC LIMIT 7; 你改成这样试试