SELECT requestID
FROM request
WHERE userId = (
SELECT userID
FROM department
WHERE desig = 'E'
AND dept = (
SELECT dept
FROM department
WHERE userId = it18
AND desig = 'FM'
)
);
答案 0 :(得分:12)
使用JOIN
编写此查询会更清楚:
select distinct r.requestID
from
request r
join department d
on d.userId = r.userID
and desig = 'E'
join department d2
on d2.dept = d.dept
and d2.desig = 'FM'
and d2.userId = 'it18'
或者,您只需将=
替换为IN
:
SELECT requestID
FROM request
WHERE userId IN (
SELECT userID
FROM department
WHERE desig = 'E'
AND dept IN (
SELECT dept
FROM department
WHERE userId = it18
AND desig = 'FM'
)
);
他们应该返回相同的结果,但要同时检查两者的性能是否存在差异。
答案 1 :(得分:6)
有两种方法可以处理它:
选项1:更改为WHERE ... IN (SELECT ...)
,如下所示:
SELECT requestID
FROM request
WHERE userId IN (
SELECT userID
FROM department
WHERE desig = 'E'
AND dept IN (
SELECT dept
FROM department
WHERE userId = it18
AND desig = 'FM'
)
);
选项2:使用像MAX()
之类的聚合函数强制只有一个结果,如下所示:
SELECT requestID
FROM request
WHERE userId = (
SELECT MAX(userID)
FROM department
WHERE desig = 'E'
AND dept = (
SELECT MAX(dept)
FROM department
WHERE userId = it18
AND desig = 'FM'
)
);