我之所以来到这里,是因为我在Oracle数据库中没有足够的经验来解决这个问题。让我解释:
我有一个表,我们会打电话给 属性 ,包含3列: ID ,属性的ID, -edit:ENTITY_ID为好,它是指/编辑-实体 , TABLE_NAME ,包含表的名称,其中的存储该属性的值,以及 Column_name ,其中包含该表中存储该值的列的名称。
在 Table_name 列中引用的每个表都包含相同的列名(例如 Value1 , Value2 等),除了第一个引用该属性链接到的实体( Entity_id )的表。
我的目标是建立一个查询,以选择每个属性(基于其ID)及其值。但是我不知道该怎么查询,因为表名和列名都发生了变化。有没有使用变量的方法?但是,如果是这样,我如何将它们放入查询中,以便它自动针对每一行进行更改?
编辑
ATTRIBUTES table ID ENTITY_ID TABLE_NAME COLUMN_NAME ---------- -------------- ------------ ----------- 1 3 Values_A Value_1 2 2 Values_B Value_3 3 2 Values_A Value_2 VALUES_A table ENTITY_ID Value_1 Value_2 Value_3 ---------- -------------- ------------ ----------- 1 Monday 42 Green 2 Sunday 3000 Blue 3 Wednesday 1 Black VALUES_B table ENTITY_ID Value_1 Value_2 Value_3 ---------- -------------- ------------ ------------ 1 Tuesday 26 Green 2 Saturday 3 Red 3 Wednesday 15 White
所以我要寻找的结果是:
RESULT: ID Value --------- ----------- 1 Wednesday 2 Red 3 3000
抱歉,如果观看起来很痛苦,制作起来也很痛苦(找不到更好的格式化方法)
使用Peter M的查询来构建SQL文本,然后利用XML的强大功能:
create table attributes (id, entity_id, table_name, column_name) as select 1, 3, 'VALUES_A', 'VALUE_1' from dual union all select 2, 2, 'VALUES_B', 'VALUE_3' from dual union all select 3, 2, 'VALUES_A', 'VALUE_2' from dual; create table values_a (entity_id, value_1, value_2, value_3) as select 1, 'Monday', 42, 'Green' from dual union all select 2, 'Sunday', 3000, 'Blue' from dual union all select 3, 'Wednesday', 1, 'Black' from dual; create table values_b (entity_id, value_1, value_2, value_3) as select 1, 'Tuesday', 26, 'Green' from dual union all select 2, 'Saturday', 3, 'Red' from dual union all select 3, 'Wednesday', 15, 'White' from dual;
询问:
with queries as ( select table_name, column_name, entity_id , 'select '|| column_name || ' as c from ' || table_name || ' where entity_id = ' || entity_id || case when id = max_id then '' else ' union all ' end as sqltext from ( select a.*, max(a.id) over (order by id) max_id from attributes a ) ) select table_name, column_name, entity_id , extractvalue(xmltype(dbms_xmlgen.getxml(sqltext)),'/ROWSET/ROW/C') as sql_result from queries;
结果:
TABLE_NAME COLUMN_NAME ENTITY_ID SQL_RESULT ---------- ----------- ---------- --------------------------------------------------- VALUES_A VALUE_1 3 Wednesday VALUES_B VALUE_3 2 Red VALUES_A VALUE_2 2 3000