0
votes

I have two tables TABLE_A with columnname COLUMN1 COLUMN2 COLUMN3 COLUMN4 COLUMN5 and which has data

abc def ghi jkl mno

123 456 789 001 121

TABLE_B with columnname COLUMN6 COLUMN7 which has data as

COLUMN5 124

COLUMN4 bca

COLUMN3 aaa

COLUMN5 bbb

So I have the columnname of Table_A as a data in the table_B

so I want to do something like this in a single query

$query1= select COLUMN6 from TABLE_B where COLUMN7='aaa';

$query2= select $query1 from TABLE_A where COLUMN1='123';

Thanks

2
Why do you want to do that? What if the first query comes back blank? ..it will break the second query.Alex W
Could you explain more extensively what you are trying to do? Could you post the desired output?Alexandre Santos
Query1 will give me column name for TABLE_A so it wont come blankuser3784040
Query1 will give output as COLUMN3 and Query2 will do select COLUMN3 from TABLE_A where COLUMN1='123' and give me result 789user3784040
Sounds like you need to wrap these two SQL statements around a programming language and have it dynamically generate the second SQL statement. It's generally inadvisable to generate dynamic SQL, but that sounds like what you're asking.Hambone

2 Answers

0
votes

You need to have a value to match from table a -> to table B If it looks like this:

TableA -> id, name
TableB -> id, table_a_id, name

This query will work:

SELECT a.name, b.name
FROM tableA as a
JOIN tableB as b ON a.id=b.table_a_id AND b.name='123'
WHERE a.name='aaaa'

To get the names of table A and B. I am using an alias for the table names here to make it easier to read. I hope, with this example, this will answer your question.

If you don't have any matching values, but you want to have all columns crossed, you can do this:

SELECT a.name, b.name
FROM tableA a, tableB b
WHERE a.name='aaa' AND b.name='123'
0
votes

You may use CASE or DECODE to do that:

select a.* from tableA a, tableB b
WHERE
b.column7 = 'aaa'
and case
when b.column6 = 'COLUMN1' then a.column1
when b.column6 = 'COLUMN2' then a.column2
when b.column6 = 'COLUMN3' then a.column3
when b.column6 = 'COLUMN4' then a.column4
when b.column6 = 'COLUMN5' then a.column5
else null end = '123' -- condition for tableA

You can make this statement up to 1000 columns (ORACLE hard limit) :)