查询从表中选择,该表是另一个表中的值

时间:2013-08-22 03:14:58

标签: sql sql-server-2008

是否可以编写如下查询?内部查询中的“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

1 个答案:

答案 0 :(得分: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

但这是一个可能无法在更大范围内解决问题的黑客攻击。