2015-11-12 40 views
0

我有一个SQL查询,我想在子查询中使用主查询的列值之一。如何在子查询中使用主查询列值?

查询是:

select **tool.item**, asset.id, tool.date, 
     (select freq from workorder 
     where type = 'CP' and itemnum = **tool.item**) freq, asset.pm 
from tool, 
    asset 
where too.num = asset.num 
    and asset.status = 'ACTIVE'; 

在此查询我想在子查询中使用获取tool.item值。

item assetid date  pm freq 

A1 1  12-NOV-15 123 freq from workorder where itemnum ='A1' 
A2 2  13-NOV-15 124 freq from workorder where itemnum ='A2' 

你能帮我吗? 在此先感谢。

+0

为什么不在工作单上使用连接? – flowit

+0

你确定你需要一个子查询吗?您期望每个工具项目有多少工单记录?如果只有1个,那么简单的加入就可以了 –

回答

0

它类似于正常join,你需要加入你的子查询与您的表列from部分 如果查询返回null或者1倍的值如果返回多个值,你将有例外

它的作品确定
select tool.item, asset.id, tool.date, 
     (select freq from workorder 
     where type = 'CP' and itemnum = tool.item) freq, asset.pm 
from tool, 
    asset 
where tool.num = asset.num 
    and asset.status = 'ACTIVE'; 
1

我强烈建议您做两件事情:

  • 学习正确的语法JOIN从未使用逗号s在from条款中。
  • 对表别名使用缩写。

所以,编写查询为:

select t.item, a.id, t.date, 
     (select wo.freq 
     from workorder wo 
     where wo.type = 'CP' and wo.itemnum = t.item 
     ) as freq, 
     a.pm 
from tool t join 
    asset a 
    on t.num = a.num 
where a.status = 'ACTIVE'; 

相关子查询是子查询使用列从外部查询的查询。在这种情况下,关联使用where子句中的t.item。当使用相关的子查询时,我非常非常强烈地建议你总是使用表别名。列名错误很容易,而且这些问题很难找到。

相关问题