If I have two tables in mysql that have similar columns…
TABLEA
id
name
somefield1
TABLEB
id
name
somefield1
somefield2
How do I structure a SELECT statement so that I can SELECT from both tables simultaneously, and have the result sets merged for the columns that are the same?
So for example, I am hoping to do something like…
SELECT name, somefield1 FROM TABLEA, TABLEB WHERE name="mooseburgers";
…and have the name, and somefield1 columns from both tables merged together in the result set.
Thank-you for your help!
Sample output appended because question unclear:
I want the rows from table1 and the rows from table2 appended in the resultset. For example if the tables contain
TABLEA
id(1) name(zoot) somefield(suit)
TABLEB
id(1) name(zoot) somefield(flute)
The resultet would look like:
name | somefield1
zoot suit
zoot flute
You can combine columns from both tables using (id,name) as the joining criteria with:
If you want to join on just the (id) and combine the name and somefield1 columns:
Although I have to admit this is a rather unusual way of doing things. I assume you have your reasons however 🙂
If I’ve misunderstood your question and you just want a more conventional union of the two tables, use something like:
This won’t combine rows but will instead just append the rows from the two queries. Use
unionon its own if you want to remove duplicate rows but, if you’re certain there are no duplicates or you don’t want them removed,union allis often more efficient.Based on your edit, the actual query would be:
(or
unionif you don’t want duplicates wherea.name==b.name=='zoot'anda.somefield1==b.somefield1).