我有一些具有相同结构的表格,我想在一组中进行选择。
我想在主查询的FROM之后放一个子查询,而不是仅仅对所有这些表进行循环。
可能会失败吗?
谢谢!
(使用Oracle)
其他信息:我没有马上的名字!它们存储在另一个表中。是否可以在主查询的FROM之后放置一个子查询?
答案 0 :(得分:11)
“我没有桌子的名字 马上!它们存储在另一个中 表“
Oracle不会在SQL中执行此类操作。您需要使用PL / SQL并组装动态查询。
create or replace function get_dynamic_rows
return sys_refcursor
is
stmt varchar2(32767) := null;
return_value sys_refcursor;
begin
for r in ( select table_name from your_table )
loop
if stmt is not null then
stmt := stmt||' union all ';
end if;
stmt := stmt||'select * from '||r.table_name;
end loop;
open return_value for stmt;
return return_value;
end;
/
这将汇总像这样的查询
select * from table_1 union all select * from table_2
UNION ALL是一个集合运算符,它将多个查询的输出组合在一个结果集中,而不会删除重复项。每个查询中的列必须与数字和数据类型匹配。
因为生成的语句会自动执行,所以格式化它没有实际价值(除非查询的实际位更复杂,你可能需要调试它)。
Ref Cursors是PL / SQL结构,相当于JDBC或.Net ResultSet。 Find out more。
答案 1 :(得分:4)
当然,只需将它们结合在一起:
select * from TableA
union all
select * from TableB
union all
select * from TableC
您可以在子查询中结合:
select *
from (
select * from TableA
union all
select * from TableB
) sub
where col1 = 'value1'
如果您只对唯一行感兴趣,请使用union
;如果您希望所有行包含重复行,请使用union all
。