Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Use Result from one Query for another Query

Tags:

sql

join

mysql

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.

like image 622
curlie Avatar asked Oct 28 '17 10:10

curlie


2 Answers

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.

like image 138
Alberto Martinez Avatar answered Oct 03 '22 10:10

Alberto Martinez


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;
like image 45
Sweety Avatar answered Oct 03 '22 10:10

Sweety