我想将变量从主查询传递到子查询。这是一个问题,因为此查询使用3个子。
我曾尝试加入,但由于我是新手,所以有点令人困惑。代码是这样的
select fav.cust_id
from
(
select cust_id
from
(
select cust_id
from
(
select c.cust_id
from customer c
)
)
)fav
where fav.cust_id = 12;
如我们所见,我试图将值'12'传递到最深的子查询(c.cust_id),以便它返回主查询中的预期值。如果我尝试在第一个子查询中传递值,它将在使用条件之前尝试从第二个子查询中获取所有数据时返回错误的数据。因此,我想做的就是在最深层子查询中传递条件,以便从那里过滤结果以返回预期值。
更新: 这是我所做的接近真实的查询。
select fav.cust_lname, fav.cust_time
from
(
select max(cust_lname), max(cust_time)
--there is another code here for some calculations
from
(
select lname cust_lname, time cust_time
--there is another code here for some calculations
from
(
select c.cust_id
--there is another code here for some calculations to return the cust_lname and cust_time
from
customer c
where cust_g = 'MALE'
AND cust_id = --in the original code, this is a parameter. i want this to read the value from the main query
)
)
)fav,
customer_table ct
where ct.header_id = --custom parameter that im trying to play with
AND ct.cust_id = --i want to relate this with the cust_id inside the sub query
答案 0 :(得分:0)
查询可以简化如下。您不需要嵌套的子查询。
select fav.cust_id
from fav
join b
on b.cust_id = fav.cust_id
join c
on c.cust_id = b.cust_id
WHERE fav.cust_id = 12
答案 1 :(得分:0)
从您给定的查询中
(
select max(cust_lname), max(cust_time)
--there is another code here for some calculations
from
(
select lname cust_lname, time cust_time
--there is another code here for some calculations
from
(
select c.cust_id
--there is another code here for some calculations to return the cust_lname and cust_time
from
customer c
where cust_g = 'MALE'
AND cust_id = --in the original code, this is a parameter. i want this to read the value from the main query
)
)
)fav
是表内查询(获取的记录用作table1数据)
使用的另一个表是
customer_table ct
并且根据您的代码,它就像将table1(fav)与第二个表联接在一起,但是在子查询中不可用。
考虑这个... 单独用于table1的代码段。...它将从那里获取ct.cust_id? ct表不在子查询中,这将导致无效的标识符错误。
按照给定的代码,您尝试通过从外部客户表中加入cust_id来获取fav.cust_lname,fav.cust_time(它们是来自子查询的值)。如果是这样,则可以将其写为
select (subquery with join from ct table) from customer_table ct
如果要在表内查询本身中使用联接
select column1, column2 from (select ....cust_id... from customer_table ctin ...)fav, customer_table ct where...
应该执行类似的操作,即在表内查询中应参照该列调用联接表
最主要的是,您已将表内查询与联接到外部表的表一起使用,而表内查询无法使用该表,或者切换到子查询或在表内查询中引入了外部表
答案 2 :(得分:0)
好的,所以我今天学到了新东西。我使用OUTER APPLY
在最深的子查询中传递值,感谢所有建议。
select fav.cust_lname, fav.cust_time
from
customer_table ct
outer apply
(
select max(cust_lname), max(cust_time)
--there is another code here for some calculations
from
(
select lname cust_lname, time cust_time
--there is another code here for some calculations
from
(
select c.cust_id
--there is another code here for some calculations to return the cust_lname and cust_time
from
customer c
where cust_g = 'MALE'
AND cust_id = ct.cust_id --match with the column in the outside query table
)
)
)fav,
where ct.header_id = --custom parameter that im trying to play with
--AND ct.cust_id = --i want to relate this with the cust_id inside the sub query --removed this