2016-03-15 158 views
-1

这是我的代码:SQL性能查询

SELECT 
    agen.id,agen.nome,agen.matricula,agen.tel_ben,agen.exames,agen.nome_contato, 
    agen.tel_contato,agen.mail,agen.periodo_contato,agen.parentesco,agen.pedido_medico,agen.status 
CASE 
    WHEN txt_data is null 
    THEN datediff(curdate(), agen.dataHora) 
    ELSE datediff(curdate(), hist.txt_data) end as txt_ultimocontato 
FROM agendamento agen 
LEFT JOIN tb_historico hist on hist.id_agendamento = agen.id 
WHERE status = 'N' 
ORDER BY txt_ultimocontato DESC 
LIMIT 0,100 

表agendamento

enter image description here

表tb_historico

enter image description here

如何提高这个查询,这个速度很慢!

+3

请发布运行'EXPLAIN 的结果;' – Asaph

+0

发布所有涉及的表结构和每个表的数据样例少数记录。最好提供http://sqlfiddle.com/ – Alex

+0

索引表议程和tb_historico。 正如其他人指出的那样,请发布EXPLAIN的结果 user2260040

回答

1

您需要在连接中涉及的任何列上的where索引,where子句和order by子句上使用索引。如果没有索引,服务器必须扫描整个表来执行这些操作,而且速度很慢。

了解如何获得和解释“解释计划”。这是调整查询性能的主要工具,您将注意到请求其中的一条。解释计划揭示索引是否被使用。

提供表定义时还包括表上的索引。

+0

更新...问题 –