功能要求 查询里记录 PType=1 and   Status=2 and  OType=1 最近一条  PType=1 and   Status=1 and  OType=1 记录,其中Status=2的Id 会大于 Status=1 的 Id,Id 是ta 表中主键
select a.*,
(select b.OperationDate from ta b where a.FileId=b.FileId and b.Status=1 and b.OType=1 and b.PType=1 order by Id desc limit 1)from  ta  a 
where  a.PType=1 and  a.Status=2 and a.OType=1
and  a.FileId=30826593

解决方案 »

  1.   

    a.FileId加索引
    b.FileId加索引
      

  2.   

    create index xxx on ta (PType,Status,OType,FileId)
      

  3.   

    加索引那是肯定的啊,这个查询是来自一个表的,FileId已经加了,ta 表大概 100w 记录,查询一下非常慢,
      

  4.   

    这个 作用 不大, create index xxx on ta (PType,Status,OType,FileId)有没有其他的写法,不要 写limit 1
      

  5.   

    这样试试
    select a.*,
    (select b.OperationDate from ta b where a.FileId=b.FileId and b.Status=1 and b.OType=1 and b.PType=1 
    and 
    not exists(select 1 from ta where FileId=b.FileId and Status=b.Status and OType=b.OType and b.PType=PType and b.id<id  ))
     from  ta  a 
     where  a.PType=1 and  a.Status=2 and a.OType=1
     and  a.FileId=30826593create index xxx on ta (PType,Status,OType,FileId,id)
      

  6.   

    复制错了,应该把and  a.FileId=30826593 这个条件去掉,查询所有的,
      

  7.   

    贴出如下结果以供分析。show index from ta ;
    explain select a.*,
    (select b.OperationDate from ta b where a.FileId=b.FileId and b.Status=1 and b.OType=1 and b.PType=1 order by Id desc limit 1)
    from  ta  a 
    where  a.PType=1 and  a.Status=2 and a.OType=1
    and  a.FileId=30826593
      

  8.   

    最后我变通了一下做法,不用 order by Id desc limit 1
     select a.*,
    (select max(b.OperationDate) from ta b where a.FileId=b.FileId and b.Status=1 and b.OType=1 and b.PType=1)
    from  ta  a 
    where  a.PType=1 and  a.Status=2 and a.OType=1