简体   繁体   中英

How to solve a SQL query that requires a second level sub-query?

I have to retrieve a sub-query with reference to data in the original query and unsure how to do it (in at least a fairly clean and efficient way).

Here's some sample data to illustrate what I'm trying to achieve:

id    original_id     flag   rec   
--    -----------     ----   ---
5           5          Y      1
6           5          N      1
7           5          N      1
8           15         N      1
9           15         N      1
10          10         Y      2
11          10         N      2

So I'm trying to select all records that have rec = 1 and original_id = (the original_id of the flag = 'Y' record)

In this example I am trying to get back the ids (5, 6, 7) since the original_id of the flag = 'Y' record is 5 and so select id where rec = 1 and original_id = 5 returns what I need.

For the record, I tried

 select id
 from table t1 join
 table t2 on t1.id = t2.id and t2.original_id = t1.original_id and t1.current = 'Y'
 where t1.id = 1

but that only returns the 'Y' record, id = 5

What is a SQL query I can use to retrieve these records? Any help would be appreciated!

It seems you have too many and's

select id
from table t1 join
table t2 on t1.id = t2.id and 
t2.original_id = t1.original_id and t2.original_id
and t1.flag= 'Y'

This should return the data you are looking for:

select t1.id
from table t1
inner join table t2
on t1.original_id = t2.id
and t2.flag = 'Y'
where t1.rec = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM