2013-08-22 132 views
-1

是否可以按如下方式编写查询?在内部查询的“column4”是表名,我要在外部查询查询从表中选择是另一个表中的值

select x.column1, x.column2, x.column3, d.column5 
    from (select 
     a.column1, a.column2, a.column3, b.column4 
    from 
     table1 a inner join table2 b on a.priKeyCol = b.prikeyCol 
    )x 
    inner join column4 d on x.column2 = d.priColKey 
+0

听起来像你需要看看使用动态SQL。 – Taryn

回答

0

你可以做的是创建一个关于你可能参加的所有表位于视图中使用它。

create view UnifiedTables 
as 
select *,'Table1' as TableName from table1 
union all 
select *,'Table2' as TableName from table2 
union all 
select *,'Table3' as TableName from table3 

然后你可以在你的主查询中加入这个UnifiedTables

select t1.c1 t1c1, t1.c2 t1c2, t1.c3 t1c3, 
     ut.c1 utc1, ut.c2 utc2, ut.c3 utc3 
from table1 t1 
join UnifiedTables ut on t1.c4 = ut.TableName 

但这是一个黑客,它可能无法解决您的问题在一个更大的规模。

+0

这不是我要找的。我正在寻找一种方法来从表中选择,表名是另一个表中的值。 – fn79

+0

@ fn79我知道。你觉得我提供什么? –

相关问题