提问人:Kimbo 提问时间:8/28/2022 最后编辑:JensKimbo 更新时间:8/28/2022 访问量:39
mysql嵌套查询 - 前三名薪水
mysql nested query - Top Three Salaries
问:
请帮我解决这个问题。有 2 个表:员工表和部门表。
正确:
select d1.name Department, e1.name Employee, e1.salary Salary
from Employee e1, Department d1
where e1.departmentId = d1.id
and
e1.salary in (
select * from (
select distinct e2.salary
from Employee e2
where e2.departmentid = e1.departmentid
order by e2.salary desc limit 3
) as t)
为什么我不能这样写这个查询?
select d1.name Department, e1.name Employee, e1.salary Salary
from Employee e1, Department d1
where e1.departmentId = d1.id
and
e1.salary in (
select * from (
select e2.departmentId, distinct e2.salary
from Employee e2
group by e2.departmentId
order by e2.salary desc limit 3
) as t)
谢谢。
答:
0赞
Bill Karwin
8/28/2022
#1
我看到两个问题:
查询中的第一个问题是 DISTINCT 是查询修饰符。您只能在 SELECT 后立即使用它。DISTINCT 适用于选择列表中的所有列,而不仅仅是一列。因此,将其放在单列之前是没有意义的。
第二个问题是,您正在将单列与子查询进行比较,因此子查询必须返回单列结果。子查询返回的每个元素必须与左操作数相当。
您也可以在常规 IN() 表达式中看到这一点。以下情况很好:
mysql> select 1 in (1, 2, 3) as ok;
+----+
| ok |
+----+
| 1 |
+----+
但是,如果您尝试将列表的每个元素都设置为元组,则无法将这些元素与左操作数进行比较:
mysql> select 1 in ((1, 'a'), (2, 'b'), (3, 'c'));
ERROR 1241 (21000): Operand should contain 1 column(s)
但是,如果左操作数也是相同程度的元组,则具有可比性:
mysql> select (1, 'a') in ((1, 'a'), (2, 'b'), (3, 'c')) as ok;
+----+
| ok |
+----+
| 1 |
+----+
评论
0赞
Kimbo
8/30/2022
感谢您的详细解释!(我之前的评论被删除了)。
评论