现在有三个表a 表500万数据,b表8000万数据,c表10万数据,
其中a表中的ReportId是主键并且a表中的companyid 加上了索引。
b表中的ReportId和其他一个字段联合成主键
c表中的companyid 为主键select * from  b where ReportId = 'sss' 单表查询数据是非常快的,这个查询非常慢,查询7000多条记录,花了690多秒,和大表关联的时候怎么优化?
select b.* from  a,   b,  c
where a.ReportId = b.ReportId and c.CompanyId=a.companyid and a.companyid = 'xxxx';这个查询是非常快的
select a.* from  a,    c
where  c.CompanyId=a.companyid and a.companyid = 'xxxx';

解决方案 »

  1.   

    同样的表结构和数据 三张表,同样的sql语句,我放到sql server2005 里面执行一下 耗时00:00:00 ,真的和mysql 是天壤之别。
      

  2.   

    b表中的ReportId字段单独建个索引看看。
    另外打印出
    explain select b.* from a, b, c
    where a.ReportId = b.ReportId and c.CompanyId=a.companyid and a.companyid = 'xxxx';
      

  3.   

    id select_type table type possible_keys key key_len ref rows Extra
    1 SIMPLE c const PRIMARY PRIMARY 32 const 1 Using index
    1 SIMPLE b ALL (NULL) (NULL) (NULL) (NULL) 57085500
    1 SIMPLE a eq_ref PRIMARY,idx_cff_cid PRIMARY 62 func 1 Using where
      

  4.   

    而且非常消耗物理内存,服务器是linux 4 cpu 8g内存,内存一下从1g 上升到7g多,只有41m剩余的。上面就是跑了一个数据库。
      

  5.   

    b的链接字段都没用上索引 试试在b.ReportId上单独写个索引 
      

  6.   


    explain
    select * from b where ReportId ='xxxx'
    显示
    id select_type table type possible_keys key key_len ref rows Extra
    1 SIMPLE b ref PRIMARY PRIMARY 20 const 1 Using where
     b表中的主键是ReportId 加上其他一个字段,看上面的explain,查询条件用ReportId 是用到了主键索引,
    为什么在join 的时候没有用到呢????
      

  7.   

    刚在b表上把原来主键删除,单独在ReportId 上建了一个索引,执行计划还是原来的,a join b,b不管怎么样必须做全表扫描
      

  8.   

    explain 
    select b.*
    from   a join   b 
    on a.ReportId=b.ReportId b中的ReportId 建立了索引,为什么显示的还是全表扫描?
      

  9.   


    这种join的实现过程就是,读一条纪录,然后到另外一个表里检索是否有这条记录
    估计mysql优化器看见您要所有的b.* 就把b放到最前面(全表扫描) 然后和a的纪录对比,得出结果!像这个语句(b表中的ReportId和其他一个字段[假设是othercolumn]联合成主键),可以试一试覆盖索引,当然这里也要分页(如0-100条纪录),要不然肯定慢select b.* from b inner join 
    (select b.ReportId,b.othercolumn from b inner join 
        (select a.ReportId from a, c where c.CompanyId=a.companyid and a.companyid = 'xxxx') ac o 
    on b.ReportId=o.b.ReportId limit 0,100
    ) as p 
    on b.ReportId=p.ReportId,b.othercolumn=p.othercolumn;
      

  10.   

    你的mysql 培植没有优化大表处理能力对比商业数据而言,有差距 ,但不会像你说那么大、
    三个表a 表500万数据,b表8000万数据,c表10万数据,
     
    这个b表到达8000万数据, mysql5。0 对千万级别的查询能力皓弱
    经历了反复的测试过 
    500万都属于大表了 。  
      另外你的windows  linux 的硬件指标需要对比的, 否则不同的条件
    没有办法比 
      

  11.   

    非常怀疑 所说的 sql server2005  的效率!
      

  12.   

    说效率, 我只相信 Mysql!