各位牛牛好:
  
   初级Java程序员一枚
   是这样的,公司领导突然有个怪需求(诅咒下),要查询用户在这段时间和另外一段时间都有的订购记录比如一张表  购买者,产品ID,购买时间  现在这张表的记录最多也就保存三个月,所以数据量在800W左右,下午自己写了一条自连接的语句  select o1.order_user from order_record o1,order_record o2 where o1.order_user=o2.order_user and o1.order_time between '2013-02-01 00:00:00' and '2013-02-07 23:59:59' and o2.order_time between '2013-02-08 00:00:00' and '2013-02-15 23:59:59';数据量300多万,order_user加了索引  查了将近两个小时 麻烦大家给个效率高的sql语句或者大家给个方案,需求就是,比如上周订购的用户,本周仍然有订购,或者是上月订购,本月仍有订购,就是两段时间内求交集的用户   小弟不胜感激啊,分都在这了mysql 查询优化

解决方案 »

  1.   

    你的sql为什么where条件里没有具体的userid=xxx
      

  2.   

    创建如下索引。create index xxx1 on order_record(order_time);
    create index xxx2 on order_record(order_user,order_time);
      

  3.   

    EXPLAIN select o1.order_user from order_record o1,order_record o2 where o1.order_user=o2.order_user and o1.order_time between '2013-02-01 00:00:00' and '2013-02-07 23:59:59' and o2.order_time between '2013-02-08 00:00:00' and '2013-02-15 23:59:59';在两表的order_user、order_time上建立复合索引
      

  4.   

    因为用户肯定是有重复购买的嘛,所以你两个时间段的用户肯定都有购买了多次的,如果加上distinct的话会不会又延时了,我先把你说的索引建一下吧,再来试下看
      

  5.   

    还有我发现用group by本来是效率还可以的,但是如果用加了索引的列去group by的话,效率简直是吓死人
      

  6.   

    select a.order_user
    from (select order_user  from [表A] where order_time between 时间点1 and 时间点2) as a ,(select order_user  from [表A] where order_time between 时间点3 and 时间点4) as b
    where a.order_user = b.order_user
      

  7.   

    select DISTINCT o1.order_user from order_record o1,order_record o2 where o1.order_user=o2.order_user and o1.order_time between '2013-02-01 00:00:00' and '2013-02-07 23:59:59' and o2.order_time between '2013-02-08 00:00:00' and '2013-02-15 23:59:59';
      

  8.   


    select o1.order_user from order_record as o1 inner join order_record aso2 on o1.order_user=o2.order_user where o1.order_time between '2013-02-01 00:00:00' and '2013-02-07 23:59:59';
    感觉后面的那个不需要