我正在寻找一种优雅的方法来从表A中选择一列,其中从表B上的查询中检索列名。
对表格B的查询会产生'col01'
表A有几列名为'col01','col02','col03',...
最终查询应该是结果
result from B | effective SQL query 'col01' | SELECT col01 FROM A 'col02' | SELECT col02 FROM A
我正在寻找没有脚本的纯SQL解决方案。它应该与Oracle和/或MySQL一起运行。
答案 0 :(得分:7)
我正在寻找没有脚本的纯SQL解决方案。
这是不可能的。您必须动态创建语句。
答案 1 :(得分:0)
在非常简单的情况下,您可以使用CASE
语句来做这件事,但这在现实世界中不太可能有用:
with a as (
select 'col_01_val_01' as col_01, 'col_02_val_01' as col_02,
'col_03_val_01' as col_03 from dual
union select 'col_01_val_02' as col_01, 'col_02_val_02' as col_02,
'col_03_val_02' as col_03 from dual
union select 'col_01_val_03' as col_01, 'col_02_val_03' as col_02,
'col_03_val_03' as col_03 from dual),
b as (
select 1 parm, 'col_01' value from dual
union select 2 parm, 'col_02' value from dual
union select 3 parm, 'col_03' value from dual)
select b.value as result_from_b,
case b.value
when 'col_01' then col_01
when 'col_02' then col_02
when 'col_03' then col_03 end as result_from_a
from a, b
where b.parm = 1;
RESULT_FROM_B RESULT_FROM_A
------------- -------------
col_01 col_01_val_01
col_01 col_01_val_02
col_01 col_01_val_03
列必须是相同的类型(或者至少在这种情况下可以表达),b
只能返回一行......当然它不是很漂亮。对于任何更复杂的事情,您需要动态SQL,因为@a_horse_with_no_name已经建议。
答案 2 :(得分:0)