我有一个table1,其中包含一列,用于存储其他表的名称。 根据表1中的值,查询应提取与表1中给出的表名相对应的数据。
例如,让存储表名的表为tablelist(tablename,tableid)
让其他存储在tablelist.tablename中的表名分别为A,B和C
基于给定的输入参数tableid, 如果表名中存储的值为“ A”,则查询应提取与以下内容等效的结果:
Select A.name from A;
如果其为“ B”,则查询应为:
Select B.type from B;
如果其为'C',则查询应为:
Select C.msg from C;
如何将其变成接受表ID作为输入的单个查询?
请咨询
答案 0 :(得分:1)
您可以尝试构建case when
:
select case tableid
when 'A' then (select name from a)
when 'B' then (select type from b)
when 'C' then (select msg from c)
end
from tbl
带有一些数据的示例:
with
tablelist(tablename, tableid) as (
select 'A', 1 from dual union all
select 'B', 2 from dual union all
select 'B', 7 from dual union all
select 'C', 3 from dual ),
a(name) as (select 'Chris' from dual),
b(type) as (select 'T800' from dual),
c(msg) as (select 'Hello' from dual)
select case tablename
when 'A' then (select name from a)
when 'B' then (select type from b)
when 'C' then (select msg from c)
end as value
from tablelist
where tableid = 7
结果T800
。