Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling of mySQL sub-query returning multiple rows

Tags:

mysql

Here is my example:

select row_x from table_1 where row_y = (select row_a from table_2 where row_b = x)

The problem that I am running into is that my query needs to return multiple rows if the subquery returns multiple rows.

Ideally it would translate to something similar to:

 'select row_x from table_1 where row_y = '<first row from subquery>' or row_y = '<second row from subquery>' etc.

How can I make this happen? Thanks!

like image 774
m r Avatar asked Apr 27 '11 17:04

m r


People also ask

How do you handle multiple rows in subquery?

Multiple Row Sub Query Multiple-row subqueries are nested queries that can return more than one row of results to the parent query. Multiple-row subqueries are used most commonly in WHERE and HAVING clauses. Since it returns multiple rows, it must be handled by set comparison operators (IN, ALL, ANY).

What would happen if more than one rows are returned from subquery?

When the subquery returns one or more rows of values, the subquery is only evaluated once and then the row(s) of values is returned to outer query to use.

Which operator is used when the sub query returns multiple rows?

Answer: B. 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.


2 Answers

You are looking for IN clause

select row_x from table_1 
 where row_y 
 IN (
     select row_a from table_2 where row_b = x
    )
like image 149
Shakti Singh Avatar answered Oct 09 '22 02:10

Shakti Singh


SELECT t1.row_x FROM table_1 t1 JOIN table_2 t2 ON t1.row_y=t2.row_a WHERE t2.row_b = x
like image 31
piotrm Avatar answered Oct 09 '22 03:10

piotrm