Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subquery returning multiple rows..how to deal with it?

Tags:

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'
      )
);
like image 527
user2175325 Avatar asked Mar 15 '13 19:03

user2175325


People also ask

What happens when subquery returns more than 1 row?

Multiple row subquery returns one or more rows to the outer SQL statement. You may use the IN, ANY, or ALL operator in outer query to handle a subquery that returns multiple rows.

Which operators are used when a subqueries that return multiple rows?

Multiple-row subqueries return more than one row of results. Operators that can be used with multiple-row subqueries include IN, ALL, ANY, and EXISTS.

What happens when a scalar subquery returns more than one value?

Scalar Subquery Expressions If the subquery returns more than one row, then Oracle returns an error.


1 Answers

It would be much clearer to write this query using 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'

Alternately, You could simply replace the = with 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'
      )
);

They should return identical results, but try both to see if there's any difference in performance.

like image 84
Michael Fredrickson Avatar answered Oct 03 '22 01:10

Michael Fredrickson