我一直在尝试优化下面的MySQL查询无济于事。目前执行时间最长为3秒:
select count( DISTINCT v.id) from
(
select sub_jobs.id from sub_jobs, main_jobs where sub_jobs.title LIKE '%abc%' and main_jobs.id=sub_jobs.parent_id
UNION ALL
select sub_jobs.id from sub_jobs, main_jobs where job_title LIKE '%abc%' and main_jobs.id=sub_jobs.parent_id
UNION ALL
select sub_jobs.id from sub_jobs, main_jobs, companies where companies.company_name LIKE '%abc%' and main_jobs.company_id=companies.id and main_jobs.id=sub_jobs.parent_id
)
as v
我想做什么:
基本表格结构:
1。 sub_jobs
2。 main_jobs
3。公司
EXPLAIN
------column titles------
id
select_type:
table
type
possible_keys
key
key_len
ref
rows
Extra
--- row 1 ----
id: 1
select_type: PRIMARY
table: <derived2>
ALL
NULL
NULL
NULL
NULL
102642
NULL
---- row 2 ----
id: 2
select_type: DERIVED
table: main_jobs
index
PRIMARY,id_index,id_industry_featured_index
id_index
4
NULL
34214
Using index
---- row 3 ----
id: 2
select_type: DERIVED
table: sub_jobs
ref
parent_id,parent_id_category_index
parent_id
4
myjobmag_myjobdb.main_jobs.id
1
Using where
---- row 4 ----
id: 3
select_type: UNION
table: main_jobs
ALL
PRIMARY,id_index,id_industry_featured_index
NULL
NULL
NULL
34214
Using where
---- row 5 ----
id: 3
select_type: UNION
table: sub_jobs
ref
parent_id,parent_id_category_index
parent_id
4
main_jobs.id
1
Using index
---- row 6 ----
id: 4
select_type: UNION
table: main_jobs
ALL
PRIMARY,id_index,id_industry_featured_index
NULL
NULL
NULL
34214
NULL
---- row 7 ----
id: 4
select_type: UNION
table: companies
eq_ref
PRIMARY
PRIMARY
4
main_jobs.company_id
1
Using where
---- row 8 ----
id: 4
select_type: UNION
table: sub_jobs
ref
parent_id,parent_id_category_index
parent_id
4
main_jobs.id
1
Using index
---- row 9 ----
id: NULL
select_type: UNION RESULT
table: <union2,3,4>
ALL
NULL
NULL
NULL
NULL
NULL
Using temporary
我尝试在没有DISTINCT的情况下使用UNION而没有显着的收益。
如何减少此查询的运行时间。
答案 0 :(得分:0)
试图减少一个条件。请尝试让我知道
select count( DISTINCT v.id) from
(
select sub_jobs.id
from sub_jobs inner join main_jobs
on main_jobs.id=sub_jobs.parent_id
where (sub_jobs.title LIKE '%abc%' OR job_title LIKE '%abc%')
UNION ALL
select sub_jobs.id
from sub_jobs, main_jobs, companies
where companies.company_name LIKE '%abc%' and
main_jobs.company_id=companies.id and
main_jobs.id=sub_jobs.parent_id
)
as v
在问题更新后修改
可以组合2个这样的查询:
select count( DISTINCT v.id) from
(
select sub_jobs.id
from sub_jobs
inner join main_jobs
on main_jobs.id=sub_jobs.parent_id
inner join companies
on main_jobs.company_id=companies.id
where companies.company_name LIKE '%abc%'
OR
sub_jobs.title LIKE '%abc%'
OR
job_title LIKE '%abc%'
)
as v
让我知道它是否有效或抛出错误
答案 1 :(得分:0)
您可以尝试使用带有union
的3查询或代替3查询但你应该看一下解释计划
select count(dictinnct sub_jobs.id )
from sub_jobs
INNER JOIN main_jobs on main_jobs.id=sub_jobs.parent_id
INNER JOIN companies on main_jobs.company_id=companies.id
where companies.company_name LIKE '%abc%'
OR main_jobs.job_title LIKE '%abc%'
OR sub_jobs.title LIKE '%abc%'