请帮我解决这个问题。有两个表:员工表和部门表。
正确:
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)谢谢。
发布于 2022-08-27 17:32:52
我看到两个问题:
查询中的第一个问题是,区分是查询修饰符。只有在选择之后才能立即使用它。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 |
+----+https://stackoverflow.com/questions/73512989
复制相似问题