sql—比较mysql中单个表中所有记录的特定属性,并找出其中最大的属性

mi7gmzs6  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(315)

我的数据库中有一个雇员表(emp),我想做的是比较所有雇员的工资,只选择那些工资高于雇员“smith”的雇员。我尝试使用self-join来实现它,但是输出不是我想要的。这是我试过的问题。

  1. select t1.SAL from emp as t1, emp as t2 where t1.ENAME!="Smith";

以下是emp表的记录:

以下是mysql中的数据库模式:

x8diyxa7

x8diyxa71#

一个选项使用子查询进行筛选:

  1. select e.*
  2. from emp e
  3. where salary > (select salary from emp where ename = 'Smith')

请注意,要使其正常工作,表中必须只有一行 ename 等于 'Smith' .
如果要使用自联接:

  1. select e.*, e1.salary smith_salary
  2. from emp e
  3. inner join emp e1 on e.salary > e1.salary
  4. where e1.ename = 'Smith'

最后,如果您运行的是mysql 8.0,还可以使用窗口函数:

  1. select *
  2. from (
  3. select
  4. e.*,
  5. max(case when ename = 'Smith' then salary end) over() smith_salary
  6. from employee e
  7. ) e
  8. where salary > smith_salary
展开查看全部
r8uurelv

r8uurelv2#

您可以使用自联接执行此操作:

  1. select e.*
  2. from employees e join
  3. employees es
  4. on es.ename = 'Smith' and e.salary > es.salary;

这假设只有一行与“smith”匹配。

相关问题