我的数据库中有一个雇员表(emp),我想做的是比较所有雇员的工资,只选择那些工资高于雇员“smith”的雇员。我尝试使用self-join来实现它,但是输出不是我想要的。这是我试过的问题。
select t1.SAL from emp as t1, emp as t2 where t1.ENAME!="Smith";
以下是emp表的记录:以下是mysql中的数据库模式:
x8diyxa71#
一个选项使用子查询进行筛选:
select e.*from emp ewhere salary > (select salary from emp where ename = 'Smith')
select e.*
from emp e
where salary > (select salary from emp where ename = 'Smith')
请注意,要使其正常工作,表中必须只有一行 ename 等于 'Smith' .如果要使用自联接:
ename
'Smith'
select e.*, e1.salary smith_salaryfrom emp einner join emp e1 on e.salary > e1.salarywhere e1.ename = 'Smith'
select e.*, e1.salary smith_salary
inner join emp e1 on e.salary > e1.salary
where e1.ename = 'Smith'
最后,如果您运行的是mysql 8.0,还可以使用窗口函数:
select *from ( select e.*, max(case when ename = 'Smith' then salary end) over() smith_salary from employee e) ewhere salary > smith_salary
select *
from (
select
e.*,
max(case when ename = 'Smith' then salary end) over() smith_salary
from employee e
) e
where salary > smith_salary
r8uurelv2#
您可以使用自联接执行此操作:
select e.*from employees e join employees es on es.ename = 'Smith' and e.salary > es.salary;
from employees e join
employees es
on es.ename = 'Smith' and e.salary > es.salary;
这假设只有一行与“smith”匹配。
2条答案
按热度按时间x8diyxa71#
一个选项使用子查询进行筛选:
请注意,要使其正常工作,表中必须只有一行
ename
等于'Smith'
.如果要使用自联接:
最后,如果您运行的是mysql 8.0,还可以使用窗口函数:
r8uurelv2#
您可以使用自联接执行此操作:
这假设只有一行与“smith”匹配。