Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

sql - Query a table and a column name stored in a table

I come here because of a problem that I am not experienced enough to solve, in an Oracle Database. Let me explain:

The tables

I have a table that we'll call Attributes, containing 3 columns : ID, the id of the attribute, -EDIT: Entity_ID as well, the entity it refers to /EDIT-, Table_name, containing the name of the table in which the value of the attribute is stored, and Column_name, containing the name of the column in that table in which is the value is stored.

Every tables referenced in the column Table_name, contains the same column names (such as Value1,Value2, etc..) except for the first one that references another entity (Entity_id), to which the attribute is linked to.

What I am looking for

My goal is to build a query that selects every attribute (based on its id) and its value. But what I don't know is how to query that since the name of table and of the column changes. Is there a way to use variables? But if so, how can I put them in the query so that it automatically changes for each row?

EDIT

EXAMPLE

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

So the result I'm looking for would be:

RESULT:
ID        Value
--------- -----------
1         Wednesday
2         Red
3         3000  

Sorry if this is painful to watch, it was as painful to make (didn't find how to format it better)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

this is ugly

but it would generate a sql statement that you could run, maybe it is not what you want

select 'select '|| column_name || ' from ' || table_name || ' where entity_id = ' || entity_id || case when id = max_id then '' else ' union all ' end
from 
  (select a.*, max(a.id) over (order by id) max_id 
   from attributes a)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...