views:

24

answers:

3

How can I select the contents of two columns that reside in different tables in a mysql database?

+2  A: 

You would need to use either a JOIN or UNION/UNION ALL.

This will depend on wht you require.

Lets say you want all values from table 1 col a and table 2 col b in seperate rows

You can use

SELECT ColA
FROM TABLE1
UNION ALL
SELECT ColB
FROM TABLE2

All Distinct Values

SELECT ColA
FROM TABLE1
UNION
SELECT ColB
FROM TABLE2

And lets say that the you want to display them in the same row, they should have some key that links them

SELECT ColA, ColB
FROM TABLE1 t1 INNER JOIN
   TABLE2 t2 ON t1.ID = t2.ID

It would also be good to note that there are different types of Sql Joins

Different SQL JOINs

  • JOIN: Return rows when there is at least one match in both tables
  • LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
  • RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
  • FULL JOIN: Return rows when there is a match in one of the tables
astander
A: 

Use a JOIN.

http://w3schools.com/SQL/sql_join.asp

Chris Clarke
A: 
SELECT fields
FROM table_a a
JOIN table_b b
ON (a.id = b.foo_id)
Coronatus