我有一个相当复杂的查询,我在其中使用多个嵌套的查询层。查询的一个要求是我从主查询中的子查询子查询中访问一个字段。但是,由于中间查询中的聚合,我无法在该查询中包含该字段。
例如
select a, d.x, f.v?
from b
join (select a, max(z), min(z), Count(y) as x
from c
join (select a, Count(t) as v
from e
) f
on f.a = c.a
Group By a
Having min(z) <> max(z)
) d
on d.a = b.a
这可能吗?
答案 0 :(得分:4)
没有。
试试这个。基本上,在层次结构上获取所需的属性(如果需要可以重命名),然后使用它们。
Select a, d.fa From b
join (select a,f.a fa from c
join (select a from e) f on f.a = c.a
) d on d.a = b.a
我还没有测试表。如果您发现更多问题,请在此处发布。
*根据更新的问题编辑*
即使在这里,逻辑仍然相同,你必须使用......
select a, d.x, d.v?
from b
join (select a, f.v, max(z), min(z), Count(y) as x
from c
join (select a, v
from e
) f
on f.a = c.a
Group By a, f.v
Having min(z) <> max(z)
) d
on d.a = b.a
或者如果您的数据库支持Scalar子查询,您可以使用..来获取最终外部查询的值。
select a, d.x, (select v from e where e.a = b.a) f_v
from b
join (select a, max(z), min(z), Count(y) as x
from c
join (select a, v
from e
) f
on f.a = c.a
Group By a
Having min(z) <> max(z)
) d
on d.a = b.a
答案 1 :(得分:1)
如果您只是将您关心的表(在本例中为e)带回From子句,那么它可能会更直接
SELECT a,
d.x,
e.v
FROM b
JOIN (SELECT a,
MAX(z),
MIN(z),
COUNT(y) AS x
FROM c
JOIN (SELECT a
FROM e) f
ON f.a = c.a
GROUP BY a
HAVING MIN(z) <> MAX(z)) d
ON d.a = b.a
JOIN (SELECT a, Count(t) as v
FROM e
GROUP BY A ) e
ON e.a = d.a