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

标签 mysql sql

我必须引用原始查询中的数据来检索子查询,并且不确定如何执行此操作(至少以相当干净和有效的方式)。

这里有一些示例数据来说明我想要实现的目标:

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

所以我试图选择所有具有rec = 1和original_id =(flag = 'Y'记录的original_id)的记录

在此示例中,我尝试取回 id (5, 6, 7),因为 flag = 'Y' 记录的original_id 为 5,因此选择 id,其中 rec = 1 且original_id = 5 返回我需要的内容。

郑重声明,我尝试过

 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

但只返回“Y”记录,id = 5

我可以使用什么 SQL 查询来检索这些记录?任何帮助将不胜感激!

最佳答案

这应该返回您正在查找的数据:

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

关于mysql - 如何解决需要二级子查询的SQL查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35945913/

相关文章:

MySQL 从 google LineChart 的 TIMESTAMP 列中获取日期的百分比

PHP/MySQL 查询中的查询

mysql - 在该月的最后一天获取上个月的数据。

mysql - 结果字段显示空白值的情况

php - 在一页内编辑/删除/列出

sql - 每个月的顶部和底部销售

sql - PostgreSQL : Getting one result per date when table has start and end date columns

mysql - Django 删除导致完整性错误(models.set_null)

mysql - 每周前 5 名记录

mysql - 在mysql的一列中创建多个值