[英]How to use main query column value in sub-query?
我有一个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'
你能帮我吗? 提前致谢。
我强烈建议您做两件事:
JOIN
语法(在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
。 在使用相关子查询时,我非常非常非常建议您始终使用表别名。 用列名犯错误很容易,而且很难找到这些问题。
它与普通join
类似,如果查询返回null或1值,则需要在列中将子查询与表中的表联接起来from
如果查询返回null或1值,则工作正常,如果返回大于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';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.