这个查询无法快速执行,为什么?

时间:2015-07-28 12:01:10

标签: mysql performance

select 
  OQSP.query_id as quries_id, 
  OQA.allocation_date_time,
  OQA.submitted_date_time,
  OQA.comment,
  OQ.*,
  p.pnr_no,
  p.pnr_generated_time,
  p.mail_status,
  p.exp_mail_status,
  p.time_validity,
  p.payment_status,
  p.payment_type 
from online_query_submit_option OQSP 
left join online_query_allocation OQA on OQSP.query_id= OQA.alloted_query_id 
left join online_queries OQ on OQSP.query_id= OQ.query_id 
left join pnr_quries as p on p.query_id=OQ.query_id 
where 
1=1 
and (OQ.confirm IS NULL OR OQ.confirm='') 
and (OQ.dead IS NULL OR OQ.dead='') 
and (OQ.running IS NULL OR OQ.running='' 
OR OQ.running='running') 
and OQA.assigned_executive='swatijoshi' 
and OQA.exec_del_status=0 
and OQ.admin_del_status=0 
and OQA.submitted_query=1 
AND date(OQ.query_date)='2015-07-28' 
group by OQSP.query_id 
order by OQ.query_date DESC,OQSP.query_id DESC 
limit 0,5 

2 个答案:

答案 0 :(得分:0)

不是一个完整的答案,但希望有一些有用的提示:

使用EXPLAIN计算查询的执行情况。

检查您正在加入的所有字段是否已编入索引,无论是仅作为主键还是其他。有时索引WHERE子句中提到的某些字段也可以提高查询速度。

您可能还想重新排序JOIN;看起来你的第一步应该是获得OQA记录,因为它们将返回一个非常有限的集合。

OQ.query_date是'date'字段还是'datetime'字段?如果是前者,您可能不需要在它周围使用date()。如果由于某种原因将其定义为VARCHAR,请将其更改为日期字段。

答案 1 :(得分:0)

不需要时请勿使用def get(self): num_entries = self.request.get(NUM_ENTRIES) if not num_entries: num_entries = CHUNK_SIZE req_cursor = self.request.get(CURSOR) cursor = Cursor(urlsafe=req_cursor) query_tuple = Animal.query().fetch_page(num_entries, start_cursor=cursor) (animals, next_cursor, more) = query_tuple if next_cursor: next_cursor = next_cursor.urlsafe() self.response.write(json.dumps({ ANIMALS: [animal.to_dict() for animal in animals], CURSOR: next_cursor, MORE: more }))

LEFT

left join online_queries OQ on OQSP.query_id= OQ.query_id ... AND date(OQ.query_date)='2015-07-28' 表示要保留OQ中缺少的行;但是LEFT会丢掉任何丢失的行。

更改

AND

AND date(OQ.query_date)='2015-07-28' 
group by OQSP.query_id 
order by OQ.query_date DESC,OQSP.query_id DESC 
limit 0,5 

并添加

AND OQ.query_date >= '2015-07-28'
AND OQ.query_date  < '2015-07-28' + INTERVAL 1 DAY
group by OQ.query_date,
         OQ.query_id          -- added to match the ORDER BY
order by OQ.query_date DESC,
         OQ.query_id DESC     -- same as OQSP
limit 0,5 

这样,优化器可以能够使用INDEX(query_date, query_id) -- to OQ 非常高效地完成GROUP BYORDER BYLIMIT

请修改您的问题以包含

INDEX

有了这些,我们可以免除一些建议/虐待。