tags:

views:

34

answers:

3

I have a SQL query like this:

SELECT *
FROM (
  (SELECT name FROM man)
  UNION
  (SELECT name FROM woman )
) AS my_table
ORDER BY name

how can I retrieve the source of my data? For example if my result is like this:

Bob
Alice
Mario
...

I want to know if the name 'Bob' is retrieve from the 'man' table or from the 'woman' table.

+4  A: 
SELECT * 
FROM ( 
  (SELECT name, 'man' as source FROM man) 
  UNION ALL
  (SELECT name, 'woman' FROM woman ) 
) AS my_table 
ORDER BY name 

I added the UNION ALL becasue if these are mutually exclusive tables, it will be faster. If they are not, then adding the source will make the results mutually exclusive and you wil be able to see where the dups are. If they are not mutually exclusive but you only want to show one record, what business rule do you want to show which record you took?

HLGEM
+1: For being first. It's what I'd do - Define an informational column, using a statically defined value that is unique from all the other queries involved.
OMG Ponies
"if these are mutually exclusive" -- what do you mean "if"? Changing `UNION ALL` to `UNION` will have no effect on the resultset.
onedaywhen
@onedaywhen, UNION is much slower than UNION ALL so UNION ALL should be used wherever possible. If you are returning the same results the differnt parts of the union are mutually exclusive and UNION ALL is the better choice.
HLGEM
I still don't see why you've used "if" in the sentence, "if these are mutually exclusive tables". How could there be duplicate rows if one table has 'man' as a literal and the other has the literal 'woman' in the same column? Ok so the base table `man` could have duplicate rows but I don't see how this would fit with a definition of "mutually exclusive".
onedaywhen
+3  A: 

A select can include a literal string, so the simplest way is probably to do:

SELECT *
FROM (
  (SELECT name, 'man' as source FROM man)
  UNION
  (SELECT name, 'woman' as source FROM woman )
) AS my_table
ORDER BY name
JacobM
`UNION ALL` will run faster than `UNION`, and the UNION ability to remove dups is not needed because there will never be any duplicates between the two parts of the UNION (because of the `source` column).
KM
+1  A: 

These will only work if there is no intersection of Man & Woman.

If you expect duplicates, you will need to add some magic to the where clause. and perhaps a 3rd query in the union to cover those where both exist.

Rawheiser
Excellent point
HLGEM