我可以在SQL的另一个“ With”中执行内部“ With”吗?

时间:2019-07-17 15:31:16

标签: sql db2 double left-join ibm-midrange

我正在尝试使用多个SQL With子句。

我使用多个With的原因是我将此SQL发送到AS400项目。 With TEMP必须是强制性的,而不是必须是可选的Temp2

我不知道该怎么做。此SQL仍然会引发错误:

With Temp2 As 
(
    With Temp As 
    (
        Select Name, Surname, Age 
        From People
        Where Age > 18
    )
    Select A.*, B.* 
    From Temp A 
    Left Join City B on B.Name = A.Name 
                     and B.Surname = A.Surname 
    Where B.City = "Venice"
)
Select * 
From Temp2 C 
Left Join State D on D.City = C.City

我想了解我该怎么做。

2 个答案:

答案 0 :(得分:6)

是的,任何CTE都可以引用在其之前创建的CTE。第一个CTE必须以“ With”开头,并以逗号结尾,以允许创建另一个CTE。

with temp as 
(
    select name, surname, age 
    from people
    where age > 18
),
temp2 as 
    (
        select a.*, b.* 
        from temp a 
        left join city b 
            on b.name = a.name 
            and b.surname = a.surname 
        where b.city = "Venice"
    )

select * 
from temp2 c 
left join state d 
    on d.city = c.city
;

这在功能上等同于下面的查询,该查询不需要任何CTE。

select *
from people as a
join city b 
    on b.name = a.name
    and b.surname = a.surname 
    and b.city = "Venice"
left join state c
    on c.city = b.city
where a.age > 18
;

答案 1 :(得分:0)

对于您所描述的内容,您既不需要CTE也不需要子查询。只需使用常规JOIN

SELECT p.Name, p.Surname, p.Age, C.City, s.StateName, s.CountryName 
FROM People p
INNER JOIN City c ON p.Name = c.Name
    AND p.Surname = c.Surname
    AND c.City = 'Venice'
LEFT OUTER JOIN State s ON c.City = s.City
WHERE p.Age > 18

有关演示,请参见https://dbfiddle.uk/?rdbms=db2_11.1&fiddle=6d16c8325ee1da354588ddddc75bb162