sql查询性能评估

but5z9lq  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(299)

我目前有两个版本的sql query,我正在努力了解哪个版本在性能、成本等方面更好。
这是关于这个问题:平均工资:部门vs公司

select department_salary.pay_month, department_id,
case
  when department_avg>company_avg then 'higher'
  when department_avg<company_avg then 'lower'
  else 'same'
end as comparison
from
(
  select department_id,
         avg(amount) as department_avg,
         date_format(pay_date, '%Y-%m') as pay_month
      from salary
      join employee on salary.employee_id = employee.employee_id
      group by department_id, pay_month
) as department_salary
join
(
  select avg(amount) as company_avg,
         date_format(pay_date, '%Y-%m') as pay_month
      from salary
      group by date_format(pay_date, '%Y-%m')
) as company_salary
on department_salary.pay_month = company_salary.pay_month
;

我的问题不是加入,而是在case语句中使用第二个表。

select a.pay_month,
       a.department_id,
       (case when avg(a.salary) > (
             select avg(e.salary)
                 from employee e
                 where e.pay_month = a.pay_month)
        then 'higher'
        else 'lower' end) as comparison
from employee a
group by a.pay_month,a.department_id;

哪个更好?加入真的有必要吗?

hl0ma9xz

hl0ma9xz1#

要确定哪个更好,您应该测试性能。有时,使用相关子查询的性能要比显式查询好得多 join 另一种选择。
当你问:“加入真的有必要吗?”我想你的意思是“是吗?” join 真的很有必要”。显然,有时可以在没有显式表达式的情况下表示查询 join . 不过,在后台,数据库正在实现一个连接算法(可能是嵌套循环或索引查找)来完成这项工作。
这基本上回答了这个问题。sql通常提供多种方法来实现相同的目标。所以,你经常可以用 join 或者没有 join . 只有一个警告:相关子查询实际上相当于 left join 而不是一个 inner join .

相关问题