现在有个很棘手的问题,小弟是新手,对mysql不是很熟悉
目前是这个样子
有10个表  
表名为demo_0,demo_1....demo_9,
这十个表的结构完全相同,但每个表都有200多万行,
我需要将这十个表union 为一个临时表,然后再跟另一个test表的字段关联小弟写的sql如下:
select * from (select * from demo_0 union all 
select * from demo_1 union all 
select * from demo_2 union all 
select * from demo_3 union all 
select * from demo_4 union all 
select * from demo_5 union all 
select * from demo_6 union all 
select * from demo_7 union all 
select * from demo_8 union all
select * from demo_9  
) as demo
left join test on test.id = demo.c_id 
where .....结果是直接跑不动,请各位大侠指点

解决方案 »

  1.   

    这十个表union压力会很大。就这段语句的话,基本上是没有优化的可能了。你尝试把left join test on test.id = demo.c_id  where ..... 这个条件放入到内部去看看。
    比如:select * from (select * from demo_0 union all  
    select * from demo_1 
    left join test on test.id = demo.c_id  
    where .....union all  select * from demo_2 
    left join test on test.id = demo.c_id  
    where .....
    ...
    ) as demo最好把整个数据操作流程贴出来,这样能更好的优化。
      

  2.   

    你的UNION all语句中,尽可能不要不加入筛选条件,这样几乎就是2000万数据了,因为10各表每次全表扫描首先就存在某些问题,是否真的需要这样做?如果不是,一定要改。如果是,那恐怕要改表结构了。比如说,10各表直接合在一起,用某些字段来区分
      

  3.   

    对2000万的表加索引然后查询会比你这样合起来查询更快,因为我也不确定你这样UNION出来的结果集再join的时候是否能用到索引
      

  4.   

    这十个表应该是称作分表吧? 结构都一样,我要统计其中的满足一个条件的字段比如bookid是1121211212的所有书的收入,我必须对这十个表进行遍历,而bookid又是存在另一个表里,直接用sql语句是查不出来,只能写程序一个表一个表的跑,然后汇总,反正很慢,我跑了5个小时才跑完
      

  5.   

    这个UNION后的结果出来应该不会用到索引吧?
      

  6.   

    如果有条件筛选,那就要先尽早筛选然后再汇总,不然数据量那么大,什么DBMS都受不了的。