为什么 UNION 不能在 CTE 或子查询中工作?

Why won't UNION work within CTE or subquery?

我正在尝试 运行 通过 System i 导航器从联合的组合结果中进行选择的查询。

这很好用:

SELECT AF15VC FROM DB.AF
UNION
SELECT AF15VC FROM BATCH.AFM

为什么这行不通?

WITH CTE AS (
    SELECT AF15VC FROM DB.AF
    UNION
    SELECT AF15VC FROM BATCH.AFM
)
SELECT *
FROM CTE

为什么这行不通?

SELECT *
FROM
    (SELECT AF15VC FROM DB.AF
     UNION
     SELECT AF15VC FROM BATCH.AFM
    ) AS AF

在这两种情况下,我都会收到此错误:

SQL State: 42601

Vendor Code: -199

Message: [SQL0199]

Keyword UNION not expected. Valid tokens: ). Cause . . . . . : The keyword UNION was not expected here. A syntax error was detected at keyword UNION. The partial list of valid tokens is ). This list assumes that the statement is correct up to the unexpected keyword. The error may be earlier in the statement but the syntax of the statement seems to be valid up to this point. Recovery . . . : Examine the SQL statement in the area of the specified keyword. A colon or SQL delimiter may be missing. SQL requires reserved words to be delimited when they are used as a name. Correct the SQL statement and try the request again.

我也试了UNION ALL,结果没有任何变化。

更新:

由于人们一直认为我没有显示实际查询,所以我添加了屏幕截图。这是第一个查询工作正常而后两个查询失败:

我在 7.2 版上工作正常

with cte as (
select pmco#, pmmanf
from dtdata.pdpmast
union 
select pmco#, pmmanf
from devqdata.pdpmast
)
select * from cte;

注意: 如果您没有或不关心重复项,请使用 UNION ALLUNION 删除重复项,如果没有任何方法,则会浪费大量处理。

您的语句应该可以正常工作。这是我的 IBM i 在 v7.2 上的测试,但它应该在 v7.1 上工作相同,或者至少根据我能找到的文档一直回到 v5r3。

create table tablea
  (field1    Char(10),
   field2    Char(10));
create table tableb
  (field1    Char(10),
   field2    Char(10));
insert into tablea
  values ('row1', 'mama'),
         ('row2', 'papa');
insert into tableb
  values ('rowa', 'timmy'),
         ('rowb', 'sissy');

然后

select * from tablea
union
select * from tableb;

给出:

FIELD1      FIELD2      
------------------------
row1        mama        
rowb        sissy       
row2        papa        
rowa        timmy       

with cte as (
  select * from tablea
  union
  select * from tableb)
select * from cte;

给予

FIELD1      FIELD2      
------------------------
rowb        sissy       
row1        mama        
row2        papa        
rowa        timmy       

select * 
from (
  select * from tablea
  union
  select * from tableb) a

给予

FIELD1      FIELD2      
------------------------
rowb        sissy       
row1        mama        
row2        papa        
rowa        timmy       

好吧,显然系统实际上是 5.1 版,而不是我在评论中所说的 7.1 版。我将我的 System i Navigator 版本误认为是数据库引擎版本(或 OS,或其他任何版本)。据我所知,真正的旧版本是问题。