Rolando
Rolando

Reputation: 62634

Can you union without overriding in mysql?

Assuming I have the following tables:

Name | Occupation
A
B
C
D
E
Workplace | Phone Number
A
B
C

I want to perform a select to merge the tables into a single table:

MyName | Type
A | Person
B | Person
C | Person
D | Person
E | Person
A | Workplace
B | Workplace
C | Workplace

How do I accomplish this? I tried:

SET @a = 'Person'
SET @b = 'Name'
SELECT Name, @a FROM tablea
UNION
SELECT Workplace, @b FROM tableb

And the output appears to be all "Person" in the second column and there are no "Workplace". What am I doing wrong?

Or is there someway I could do something like get the following from a single SELECT statement:

MyName
A_Person 
B_Person 
C_Person 
D_Person 
E_Person 
A_Workplace
B_Workplace
C_Workplace

Note: I am using MySQL Workbench

Upvotes: 0

Views: 277

Answers (2)

Bohemian
Bohemian

Reputation: 425033

Use UNION ALL instead of UNION:

SELECT Name, @a FROM tablea
UNION ALL
SELECT Workplace, @b FROM tableb

UNION removes duplicate (and in most databases sorts the results too).

UNION ALL keeps all rows in the order selected.

Upvotes: 0

Neil
Neil

Reputation: 55402

I couldn't get sqlfiddle to accept your query, but it did accept this:

SELECT Name, 'Person' FROM tablea
UNION
SELECT Workplace, 'Workplace' FROM tableb

Upvotes: 1

Related Questions