我有一个用于检索表数据的查询。当返回的行数超过3-4时,查询速度非常慢,我不明白为什么。
这是我的查询:
select
ig.id,
ig.username,
ig.created,
ig.is_completed,
ig.user_id,
ig.is_error,
ig.last_appeal_process_update,
(unix_timestamp() - ig.created) as time_running,
ig.is_deleted,
ap.id as appealprocessid,
(case
when ap.id is null then 0
when ap.id is not null then ap.status
end
) as current_status,
( select count(*) from appeal_process where ig_account_id = ig.id)
as total_appeals
from instagram_accounts ig
left join appeal_process ap on ig.id = ap.ig_account_id
where
(ig.username like CONCAT('%',?,'%') or ig.id like CONCAT('%',?,'%') or ig.username like CONCAT('%',?,'%')) and
ig.user_id = ? and is_deleted = 0 and
(
ap.id is null or
ap.id = ( -- WE SELECT ONLY THE LATEST APPEAL PROCESS
select max(id) from appeal_process tmp where tmp.ig_account_id = ig.id limit 1
)
)
order by ig.username asc
limit ?,?
编辑
这是EXPLAIN查询(尽管我不知道如何阅读)enter image description here
这是instagram_accounts
的SHOW CREATE TABLE:enter image description here
这是appeal_process
的SHOW CREATE TABLE:enter image description here
[您的问题很可能是由于缺少索引而引起的,有必要对WHERE
和JOIN
子句中使用的字段建立索引。
为这些字段中的每个字段创建索引:
ig_account_id
ig.id
ig.username
is_deleted
ig.user_id
tmp.ig_account_id