tags:

views:

100

answers:

5

If I have two tables:

Actor:
ID | Name
1  : Patrick
3  : Emma
7  : Vanessa

Singer:
ID | Name
4  : Will
5  : Madonna
13 : Emma

Can I generate the following table from an SQL query, which contains the table name each record came from?

ID | Career | Name
1  : Actor  : Patrick
3  : Actor  : Emma
4  : Singer : Will
5  : Singer : Madonna
7  : Actor  : Emma
13 : Singer : Emma

I'm assuming the ID column items are unique across the two tables, but not the names.

+9  A: 
select ID, 'Actor' as Career, Name from Actor
union all
select ID, 'Singer' as Career, Name from Singer

Or something along these lines.

Anton Gogolev
I'm accepting this answer, but I note that it doesn't actually answer the question. The *table name* does not appear in the result, rather there is a constant that happens to be the same. I'm assuming my actual question can't be answered in SQL.
John McAleely
+3  A: 
SELECT ID, 'Actor' AS Career, Name FROM Actor
UNION
SELECT ID, 'Singer' AS Career, Name FROM Singer
Yannick M.
It's a nitpick, but you should use UNION ALL if you don't need duplicates removed.
Dave Costa
It's not a nitpick. You are exactly right. If there were a unique constraint on (Id, Name) UNION ALL would effectively yield the same result as UNION, but only faster. But honestly I wouldn't care for duplicate records in this case.
Yannick M.
+2  A: 

Since you know the table names you're querying from you can simply include the table name as a literal value in the result set:

SELECT ID, 'Actor', Name FROM Actor
  UNION SELECT ID, 'Singer', Name FROM Singer;
Larry Lustig
+2  A: 

Try:

select id, 'Actor' as Career, Name
from Actor
union
select id, 'Singer' as Career, Name
from Singer
Matt Lacey
+4  A: 

OK, two people beat me to the sample query I was posting.

But, I think the better answer to your root question is, if "Career" is a relevant attribute in your data, and the IDs are expected to be unique, why not have one table in which Career is an actual column?

Dave Costa
+1 While others, as me (already deleted), were answered as asked, this one is the best answer, actually.
Viktor Jevdokimov
Normalization is for suckers :p This is the eternal tradeoff between answering the question, or solving his problem :)
Yannick M.
It's part of a larger problem, reduced for the purposes of asking a question on SO. I'm trying to figure out a minimally disruptive way of adding a minor feature.
John McAleely