SQL 语句运行缓慢 - 有啥想法吗?
Posted
技术标签:
【中文标题】SQL 语句运行缓慢 - 有啥想法吗?【英文标题】:SQL Statement Running Slow - Any Ideas?SQL 语句运行缓慢 - 有什么想法吗? 【发布时间】:2013-09-25 09:10:01 【问题描述】:不确定下面的语句是怎么回事。运行时间超过 5 分钟 - 当我将主语句包装在一个 select 中并将其别名为 temp 时,它才开始显示出真正的减速,但这样做从未减慢我的任何其他 SQL。有任何想法吗?我在 mysql 上。
select *
from (
select emp.company
, emp.employee
, emp.last_name "Last Name"
, emp.first_name "First Name"
, emp.middle_init "Middle Initial"
, trim(last_name) || ', ' || trim(first_name) ||
decode(trim(middle_init),'','',' '|| trim(middle_init)|| '.') "Full Name"
, emp.emp_status
, emp.work_country "Country"
, (select
(Case pgs.group_name
when 'HREMEA' then 'EMEA'
when 'HRNAMER' then 'NA'
when 'HRLAMER' then 'LA'
when 'HRAPAC' then'APAC'
end)
from lawson.pgselect pgs
where pgs.begin_value = emp.work_country
and pgs.company = 1
and pgs.group_name in ('HREMEA','HRNAMER','HRLAMER','HRAPAC') ) "Region"
, emp.department "Department"
, (select trim(r_name)
from lawson.deptcode dpt
where company = emp.company
and trim(process_level) = trim(emp.process_level)
and trim(department) = trim(emp.department)) "Department Description"
, emp.job_code "Job Code"
, (select description
from lawson.jobcode jbc
where company = emp.company
and job_code = emp.job_code) "Job Title"
, emp.supervisor
, (select trim(last_name) || ', ' || trim(first_name) ||
decode(trim(middle_init),'','',' '|| trim(middle_init)|| '.')
from lawson.employee supv
where supv.company = 1
and supv.position = emp.supervisor
and term_date = '01-JAN-1700') "Supervisor Name"
, (select a_field
from lawson.hrempusf
where company = emp.company and employee = emp.employee
and field_key = '99') "Alt Mgr"
, (select a_field
from lawson.hrempusf
where company = emp.company and employee = emp.employee
and field_key = '79') "TE Proxy Approver"
, (select a_field
from lawson.hrempusf
where company = emp.company and employee = emp.employee
and field_key = '76') "Time Entry Proxy 1"
, (select a_field
from lawson.hrempusf
where company = emp.company and employee = emp.employee
and field_key = '77') "Time Entry Proxy 2"
from lawson.employee emp
where term_date = '01-JAN-1700'
) temp
where temp."TE Proxy Approver" <> ' '
or temp."Time Entry Proxy 1" <> ' '
or temp."Time Entry Proxy 2" <> ' '
【问题讨论】:
我认为使用JOIN
而不是从同一个表中进行多次选择可以加快速度。取决于数据量。“慢”是相对的 - 如果查询每隔几个小时运行一次,5 分钟并不是很长的时间。
【参考方案1】:
用join替换子查询,并确保表有索引
【讨论】:
我会试一试的。谢谢。【参考方案2】:快速查看您的查询:
子查询太多,用连接替换它们 在 field_key 和 term_date 上缺少索引 不需要临时子查询,将 where 移到主查询中(联接中的数据更少)【讨论】:
如果我将 where 移到我的主查询中,我无法指定“TE Proxy Approver”等,因为它们是别名......还是我遗漏了什么? 您应该进行内部联接而不是子查询,并在联接条件中指定条件以上是关于SQL 语句运行缓慢 - 有啥想法吗?的主要内容,如果未能解决你的问题,请参考以下文章
从 PHP 程序运行的 SQL 列名上加上 '' 有啥效果吗?
使用 aws fargate 有啥缺点(缺点)以及为啥我的 laravel 应用程序在 Fargate 与弹性 beantalk 上运行缓慢?
SQL 2008 R2 - Reporting Services,通过 Internet 使用带有 Report Builder 3 的数据模型导致崩溃,有啥想法吗?