子查询返回多行..如何处理它?

时间:2013-03-15 19:28:40

标签: mysql subquery

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'
      )
);

2 个答案:

答案 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'
      )
);