select distinct i.买家会员名 from items09to11 i
join product09to11 p
on i.订单编号 = p.订单编号
where i.订单状态 = '交易成功'
and YEAR(i.订单创建时间)= 2011
and MONTH(i.订单创建时间)= 3
and p.订单状态 = '交易成功'
and p.zid != '101204'
and i.买家会员名 not in(
select distinct i.买家会员名 from items09to11 i
join product09to11 p
on i.订单编号 = p.订单编号
where i.订单状态 = '交易成功'
and YEAR(i.订单创建时间)= 2011
and MONTH(i.订单创建时间)= 3
and p.订单状态 = '交易成功'
and p.zid = '101204')查询速度30秒,数据量不大,items09to11 10万行,product09to11 15万行
zid字段一共800行,是商品代码,就是这个'101204'很慢,用其他的商品代码查询速度正常,不到1秒就出来了
请问什么问题??把这个'101204'换个随便名字,比如'bbb',就正常了
还有,我的查询目的是得到2011年3月,没有买商品 '101204'的人,有没有比上面代码简单点的,请高手赐教,

解决方案 »

  1.   

    应该有简单点的,比如你试试下面这个,应该结果和你的查询结果一样:
    select distinct i.买家会员名
    from items09to11 i join product09to11 p on i.订单编号 = p.订单编号
    where i.订单状态 = '交易成功' and YEAR(i.订单创建时间)= 2011
    and MONTH(i.订单创建时间)= 3 and p.订单状态 = '交易成功'
    and p.zid != '101204'
      

  2.   


    --你后面那段not in根本没用,直接去掉,然后year和month用不到索引,改如下方式
    select distinct i.买家会员名 from items09to11 i join product09to11 p
    on (i.订单编号=p.订单编号)
    where p.订单状态='交易成功' and p.zid!='101204' and i.订单状态='交易成功' 
    and i.订单创建时间>='2011-3-1' and i.订单创建时间<'2011-4-1'
      

  3.   

    select distinct i.买家会员名 from items09to11 i
    where i.订单状态 = '交易成功'
    and YEAR(i.订单创建时间)= 2011
    and MONTH(i.订单创建时间)= 3
    and not exists(select 1 from product09to11 
               where 订单编号=i.订单编号 and zid='101204' and 订单状态 = '交易成功')
      

  4.   

    select distinct i.买家会员名 from items09to11 i join product09to11 p
    on (i.订单编号=p.订单编号)
    where p.订单状态='交易成功' and p.zid!='101204' and i.订单状态='交易成功' 
    and i.订单创建时间>='2011-3-1' and i.订单创建时间<'2011-4-1'
      

  5.   

    --如果下面这段代码不够快,请把你建了哪些索引说出来看下
    select distinct i.买家会员名 from items09to11 i join product09to11 p
    on (i.订单编号=p.订单编号 and i.订单状态=p.订单状态)
    where i.订单创建时间>='2011-3-1' and i.订单创建时间<'2011-4-1'
    and p.订单状态='交易成功' and p.zid!='101204' 
      

  6.   

    ;with cte as(
    select i.买家会员名,p.zid
    from items09to11 i join product09to11 p on i.订单编号 = p.订单编号
    where i.订单状态 = '交易成功' and YEAR(i.订单创建时间)= 2011
    and MONTH(i.订单创建时间)= 3 and p.订单状态 = '交易成功'
    )
    select distinct 买家会员名 from cte a 
    where not exists(select 1 from cte where 买家会员名=a.买家会员名 and zid<>'101204')
      

  7.   

    not in 的效率和后面的数据多少有关系,不建议使用not in 和in 。
      

  8.   

    not  in 改成 not exists 看看  别的改的话就应该不会有多大的变化。另外看看你建的索引。  
      

  9.   

    谢谢楼上高手答复,我加not in 的目的的把没有买‘101204’的人帅选掉,因为一个人可以有多张订单,所以只用!= ‘101204’只是把非‘101204’的订单帅选出来,但这些订单可能包括购买了‘101204’的人
      

  10.   


    --have a try
    ;with cte as(
    select i.买家会员名,p.zid from items09to11 i join product09to11 p
    on (i.订单编号=p.订单编号 and i.订单状态=p.订单状态)
    where i.订单创建时间>='2011-3-1' and i.订单创建时间<'2011-4-1' and p.订单状态='交易成功'
    )
    select distinct 买家会员名 from cte a where not exists(
    select 1 from cte where 买家会员名=a.买家会员名 and zid='101204'
    )