I have an SQL query where I want to use one of the column value of the main query in the sub query.
The query is:
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';
In this query I want use the fetched tool.item value in the sub query.
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'
Could you help me with this? Thanks in advance.
答案 0 :(得分:1)
I strongly encourage you to do two things:
JOIN
syntax (never use commas in the from
clause.So, write the query as:
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';
A correlated subquery is a query where the subquery uses columns from the outer query. In this case, the correlation uses t.item
in the where
clause. When using correlated subqueries I very, very, very strongly recommend that you always use table aliases. It is very easy to make mistakes with column names, and these problems can be quite hard to find.
答案 1 :(得分:0)
it's similar to normal join
, you need join you subquery in column with your tables in from
section
if the query returns null or 1 value it works ok
if it returns more than 1 value you will have exception
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';