哪位大神 可以帮我看一下,这条 SQL,还能优化吗?select * from (select * from (SELECT shipper_code,logistic_code from tp_express where subscribe_state=2 and is_subscribe = 0 ORDER BY subscribe_time) t1 union all select * from (SELECT shipper_code,logistic_code from tp_express where subscribe_state=0 and is_subscribe = 0 ORDER BY receive_time) t2)t3 limit 0,10

解决方案 »

  1.   

    SELECT shipper_code,logistic_code from tp_express where (subscribe_state=2 and is_subscribe = 0) or (subscribe_state=0 and is_subscribe = 0) ORDER BY receive_time试试这个可以不
      

  2.   

    同一张表,根据 subscribe_state=0 不同, 排序时间也不同;你写的 就用一个时间排序吗?
      

  3.   


    SELECT shipper_code,
           logistic_code
    FROM   tp_express
    WHERE  (subscribe_state = 2 OR subscribe_state = 0)
           AND is_subscribe = 0
    ORDER BY subscribe_time
    limit 0,10这样应该可以
      

  4.   

    不知道行不行没测试:SELECT  shipper_code ,
            logistic_code
    FROM    tp_express
    WHERE   subscribe_state IN ( 0, 2 )
            AND is_subscribe = 0
    ORDER BY CASE WHEN subscribe_state = 2 THEN subscribe_time
                  ELSE receive_time
             END
    limit 0,10                        
      

  5.   


    --按照你写的语句可以看出每个结果集有自己的排序 只是单纯的做个拼接
    --union后保持各自原有排序,因此subscribe_state为2的会排在前面,其次是subscribe_state = 2的再按subscribe_time排序,为0的按receive_time
    --综合一下就是这样了
    SELECT shipper_code,
           logistic_code
    FROM   tp_express
    WHERE  (subscribe_state = 2 OR subscribe_state = 0)
           AND is_subscribe = 0
    ORDER BY subscribe_state desc,CASE WHEN subscribe_state = 2 THEN subscribe_time
                  ELSE receive_time
             END
    limit 0,10
      

  6.   

    如果  limit 0,10 是一个确定值,可以在最里面加上这个
    如果满足条件的记录少,则条件字段加上索引,确保能够快速筛选数据就行了
    如果满足条件的记录多,则比较麻烦此,因为你是在两个字段上排序,通常建议改表结构,在表上加一个生成列
    alter table tp_express add order_date as(
    case when subscribe_state=2 and is_subscribe = 0 then  subscribe_time
    when subscribe_state=0 and is_subscribe = 0 then receive_time end)这样你只需要在这个计算列上建个索引,就可以搞定排序和条件
    SELECT shipper_code,logistic_code from tp_express
    where order_date is not null
    order by order_date
    limit 0, 10