--rm_customer_user  用户表 字段 CustomerId 客户ID,UserName 用户名,Mobile 手机号码,Status 状态
--rm_customer_company 用户公司表 CustomerId 客户ID(FK) Company 公司名称 ProjectId 产品类型
--rm_agent_user 代理商表 AgentId 代理ID(FK) Company 代理商公司名称
--rm_agent_customer 代理商绑定客户表 AgentId 代理ID(FK) CustomerId客户ID(FK) ProjectType产品类型
SELECT u.CustomerId,u.UserName AS UserName,u.Mobile AS Mobile,company.Company AS Company,u.`Status`,z.Company AS agentCompany FROM rm_customer_user AS u 
LEFT JOIN rm_customer_company AS company ON u.CustomerId=company.CustomerId AND company.ProjectId=3 
LEFT JOIN 
(SELECT `t`.`CustomerId` AS `CustomerId`,`a`.`Company` AS `Company` from `rm_agent_customer` `t`  LEFT JOIN `rm_agent_user` `a` ON `a`.`AgentId` = `t`.`AgentId`  WHERE `t`.`ProjectType` = 3 
) AS z 
ON z.CustomerId=u.CustomerId;
查询3号产品用户基本信息以及对应3号产品公司名称,外加3号产品代理商公司名称
语句执行时间看效率 第一次
7S
第二次
1.272s
第三次
0.912s和mysql缓存有一定的关系

解决方案 »

  1.   

    rm_agent_customer的ProjectType上加索引
      

  2.   

    我看你给的建表语句没有rm_agent_customer的ProjectType索引
      

  3.   

    索引没贴上来,agentId customerId 都有索引 3000多的数据就这样了
      

  4.   

    rm_customer_user 使用了全表扫描,所以这里要加索引!
    <deriverd2>这里也是全表扫描,需要建索引!
    <deriverd2>,它是从第二个select中出来的,都是在select from子句中的select这么复杂的SQL,建议你拆开,这样查询真的很慢,也不好优化!我以前有条SQL也很SQL,结果也是全表扫描,加索引,强制使用索引,结果还是一样!一但拆开速度就快了!这一步都没做好,加缓存干嘛呢!越往后查询越慢。