Oracle UNION 和 ORDER BY 的奇怪问题
技术问答
244 人阅读
|
0 人回复
|
2023-09-12
|
以下查询在几乎所有数据库(提供或采用虚拟表)中都完全有效dual,包括 Oracle:( K2 D- S6 u" N6 R$ ]5 L8 |
select 'A' as x from dual union allselect 'B from dualorder by x asc$ E/ L! Z S. t5 l" S+ _1 J
返回:
) v% Z* X l$ N. L; d| X ||---|| A || B |! V, U9 Q2 b/ X* H. U! l
现在这个查询还是挺标准的 SQL,但在 Oracle 不起作用2 E* y. `* y' _9 F6 i" g! ]
select 'A' as x from dual union allselect 'B from dual union allselect 'C from dualorder by x asc5 D& _& m9 h+ W0 c/ I
我越来越" q! s- |# C# h
ORA-00904: "X": invalid identifier
: B% Q3 o9 t6 E) H0 P% s 但是,这是有效的:
+ s# H( ?+ q, i- j/ Tselect 'A' as x from dual union allselect 'B' as x from dual union allselect 'C from dualorder by x asc
% n* O+ |0 Q4 i& W! x v1 V3 H) x 我一直在解决这个问题,发现至少第一个子选择和倒数第二个选择 子需要有一个名字x. 在第一个例子中,两个子的选择似乎只是重叠。工作示例:, |; p+ f2 e+ e) S, T* R
select 'A' as x from dual union allselect 'B from dual union allselect 'C from dual union allselect 'D from dual union allselect 'E from dual union allselect 'F' as x from dual union allselect 'G from dualorder by x asc
& ?1 D }( h3 q0 N$ f. E% b 你可能已经猜到了,这行不通:
# }% q3 U) h1 I" o4 E. o* Gselect 'A' as x from dual union allselect 'B from dual union allselect 'C from dual union allselect 'D from dual union allselect 'E' as x from dual union allselect 'F from dual union allselect 'G from dualorder by x asc, b+ b+ S: h7 S. [ l
有趣的旁注:派生表似乎不受此限制。
# H F: t2 v& P7 T1 G* Q5 b: _7 Tselect * from ( select 'A' as x from dual union all select 'B from dual union all select 'C from dual)order by x asc
7 n. d, a+ F4 P" ?: m: V* y5 j 问题:这是 Oracle SQL 分析器中的(已知的?)错误,或者语言语法中是否有非常微妙的细节,绝对需要第一个和倒数第二个子选择来保存ORDER BY子句中引用的名称列? i0 M. `- p, [% f J
" M" ]( }8 q: ]
解决方案: |
|
|
|
|
|