curlie
curlie

Reputation: 295

SQL Use Result from one Query for another Query

This is an excerpt from one table:

| id | type    | other_id | def_id | ref_def_id|
| 1  | int     | NULL     |  5     | NULL     |
| 2  | string  | NULL     |  5     | NULL     |
| 3  | int     | NULL     |  5     | NULL     |
| 20 | ref     | 3        |  NULL  | 5        |
| 21 | ref     | 4        |  NULL  | 5        | 
| 22 | ref     | 5        |  NULL  | 5        |  

What I want is to find entries with type ref. Then I would for example have this one entry in my result:

| 22 | ref     | 5        |  NULL  | 5        |  

The problem I am facing is that I now want to combine this entry with other entries of the same table where def_id = 5.

So I would get all entries with def_id = 5 for this specific ref type as result. I somehow need the output from my first query, check what the ref_def_id is and then make another query for this id.

I really have problems to understand how to proceed. Any input is much appreciated.

Upvotes: 14

Views: 66433

Answers (4)

Ruchi
Ruchi

Reputation: 5192

use below query to get column from sub query.

select a.ref_def_id
from (select ref_def_id from YourTable where type='ref') as a;

Upvotes: 2

Alberto Martinez
Alberto Martinez

Reputation: 2670

If I understand correctly you need to find rows with a type of 'ref' and then use the values in their ref_def_id columns to get the rows with the same values in def_id. In that case you need to use a subquery for getting the rows with 'ref' type and combine it using either IN or EXISTS:

select *
from YourTable
where def_id in (select ref_def_id from YourTable where type='ref');

select *
from YourTable
where exists (select * from YourTable yt
  where yt.ref_def_id=YourTable.def_id and yt.type='ref')

Both queries are equivalent, IN is easier to understand at first sight but EXISTS allow more complex conditions (for example you can use more than one column for combining with the subquery).

Edit: since you comment that you need also the id from the 'ref' rows then you need to use a subquery:

select source_id, YourTable.*
from YourTable
join (select id as source_id, ref_def_id
      from YourTable
      where type='ref')
as refs on refs.ref_def_id=YourTable.def_id
order by source_id, id;

With this for each 'ref' row you would get all the rows with the associated ref_id.

Upvotes: 12

Gordon Linoff
Gordon Linoff

Reputation: 1269443

You would seem to want aggregation:

select max(id) as id, type, max(other_id) as other_id,
       max(def_id) as def_id, ref_def_id
from t
where type = 'ref'
group by type, ref_def_id

Upvotes: 0

Andre
Andre

Reputation: 4625

What you are looking for is a subquery or even better a join operation.

Have a look here: http://www.mysqltutorial.org/mysql-left-join.aspx

Joins / the left join allows you to combine rows of tables within one query on a given condition. The condition could be id = 5 for your purpose.

Upvotes: 0

Related Questions