SQL select 语句 union all with itself

标签 sql oracle plsql

您好,我有一个非常复杂的 sql 语句,它会返回一些结果。
部分结果在另一个具有相同Id的表中。
我想要一个像第一个一样的结果集加上属于另一个表的所有行的副本。

下面的代码是错误的,但显示了我正在努力实现的目标:

Select myRules.* 
From (Complicated sql statement) myRules
Union All
Select from myRules 
inner join Table2
on myRules.Id =Table2.Id;

这可能吗?

PS1。复杂的sql语句我不想碰。
PS2。我得到的错误是 myRules 表或 View 不存在

编辑:根据您的回答,我尝试创建一个返回游标的过程,但在打开游标的行中出现错误:

procedure Get_Rules(in_Id      in tableA.Reconciliation_Id%type,
                    io_cursor  in out t_ref_cursor) is
begin
With  myRules as (
 complicated sql statement)

open io_cursor for   -- ERRORS here: missing SELECT keyword
select *
   from myRules
   union all
select * 
  from myRules 
  inner join Table2
  on myRules.Id = Table2.Id;
end Get_Rules;

最佳答案

是的,union all 一个查询与同一个表上的另一个查询是完全有效的。在这种情况下最好使用 with:

with myRules as (
  complicated sql statement
)
select *
from myRules
union all
select * 
from myRules 
inner join Table2
on myRules.Id = Table2.Id;

如果要在游标中使用 with,请将其嵌入到游标中,而不是存储过程中:

procedure Get_Rules(in_Id      in tableA.Reconciliation_Id%type,
                    io_cursor  in out t_ref_cursor) is
begin
  open io_cursor for
  with  myRules as (
   complicated sql statement
  )
  select *
  from myRules
  union all
  select * 
  from myRules 
  inner join Table2
  on myRules.Id = Table2.Id;
end Get_Rules;

关于SQL select 语句 union all with itself,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35227808/

相关文章:

SQL Server 删除字符串中小数点后的尾随零

MySQL,同时在内部和外部查询中进行分组

mysql - 选择没有特定值(value) child 的 parent

python - cx_Oracle : How do I connect to Oracle when you use a Wallet?

Java、Swing、sql-我可以将文本字段中输入的值与数据库中的两列相匹配吗

java - 无法在 debian 上运行 sqldeveloper

oracle - Grails:自定义ID-年,后跟递增数字

sql - 除了架构所有者之外,其他用户不会触发架构上的 Oracle 触发器

sql - DB2 触发器语法之前

json - Oracle PL/SQL - 删除特定字符的最后一个实例