tags:

views:

63

answers:

2

Hi everyone...

Consider i am using join on three tables to get a desired result-set...

Now in that result set, is there anyway that i can find out which row comes from which table...?

Update : I see that i have phrased the question rather wrongly.... As pointed in one of the answers below, a result-set returned by join may will contain a row made up columns from multiple talbes...

So the question should actually be "Consider i am using union on three tables to get a desired result-set..."

+3  A: 

If you are asking this question, then your database is probably not structured correctly. (correctly being a subjective term).

A proper SQL query on a normalized database should not depend, nor be concerned with, where the data comes from.

Each row would be a combination of all tables, with null values being inserted in columns for left/right/outer joins which do not match the joining criteria. You could perhaps test if a column (from a particular table) is null, and derive from that that the non-null values must originate from the opposite table(s).

Then again, if you were actually performing an UNION, as Marcelo suggested, you would have to look at ancillary columns to determine the source of the data, as that information is lost in the combination.

dar7yl
+1 for a nice answer.... Can you plz elaborate on the 'ancillary' columns...?
SpikETidE
for instance, a column `origin` contains '1' if from table a, '2' if from table b, and '3' from table c.
dar7yl
Oh... Just now had this thought myself... But i thought of adding an extra character to the id string and identify the table that way.... like if it's from tbl 1 then the id will start with a, if tbl2 then b..etc...
SpikETidE
+4  A: 

You can add a table identifier column to each:

select 'A' as table_name, col1, col2 from A
union
select 'B' as table_name, col1, col2 from B
union
...

This returns a single result set which is handled by your application as any ordinary select statement:

while ( rows available ) {
  row = fetchrow
  if row.table_name == 'A' then 
     do special handling for table A
  else if row.table_name == 'B' then
     do special handling for table B
  else if ...

}

The actual syntax is dependent on the language you are using, but most procedural languages follow the scheme above.

Martin
What will be the syntax to reference these rows in the result-set...?
SpikETidE
All the rows appear as if selected from a single table. I have added an extra section to the answer to show how to handle these.
Martin
Thanks for the suggestion..... +1 for letting me learn a new trick...
SpikETidE