简体   繁体   English

如何解决需要二级子查询的SQL查询?

[英]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) 因此,我试图选择具有rec = 1和original_id =(标志的original_id ='Y'记录)的所有记录。

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. 在此示例中,由于标志='Y'记录的original_id为5,因此我尝试获取id(5、6、7),因此select id where rec = 1 and original_id = 5返回我需要的内容。

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 但这只会返回“ Y”记录,id = 5

What is a SQL query I can use to retrieve these records? 我可以用来检索这些记录的SQL查询是什么? 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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