mysql join two tables- how to give different value based on where the value originally come from?

Issue

let’s say I have two table A, B


    A: NAME, ID, BIRTHDAY, COUNTRY
---------------------------------------
       john, ab123, 12/21/1999, USA
       JANE, as111, 11/02/1956, FRANCE

    B: NAME, ID, SALARY
---------------------------------------
       MARY, AS111, 12333


I WANT TO JOIN TWO TABLES WITH THESE COLUMNS :
NAME, ID, FROM_WHERE
-------------------------------
john, ab123, 'A'
JANE, as111, 'A'
MARY, AS111, 'B'

FROM_WHERE shows "A" if the value is originated from A, and "B" if the value is originated from B.

SELECT NAME, ID FROM A JOIN B USING (NAME, ID)

With the query above, what should I add to get the FROM_WHERE value?

Solution

you can use UNION to do that like:

SELECT NAME, ID, 'A' as FROM_TABLE from A 
UNION ALL
SELECT NAME, ID, 'B' as FROM_TABLE from B 
ORDER by NAME;

Answered By – Bernd Buffen

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published