我可以在 SQL 中的另一个 "With" 中做一个内部 "With" 吗?

Can i do a inner "With" inside another "With" in SQL?

我正在尝试使用多个 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

我想了解如何才能做到这一点。

是的,任何 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
;

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

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