Complex MySQL query with multiple select statements

Daniel Berthiaume picture Daniel Berthiaume · Mar 1, 2013 · Viewed 17.9k times · Source

I have three tables in Mysql that are link together:

Profile (ID, Name, Stuff..)

Contact(ID, ProfileID,desc,Ord)

Address(ID,ProfileID, desc, Ord)

Now I need to select all profile from the profile table, with the “desc” field from Contact and Address where Ord = 1. (this is for a search function where in a table I’ll display the name, main contact info and main Address of a client.

I can currently do this with three separate SQL request:

SELECT Name, ID FROM Profile WHERE name=”bla”

Then in a foreach loop, I’ll run the other two requests:

SELECT ProfileID, desc FROM Contact WHERE ProfileID=MyProfileID AND Ord=1
SELECT ProfileID, desc FROM Address WHERE ProfileID=MyProfileID AND Ord=1

I know you can do multiple SELECT in one query, is there a way I could group all three SELECT into one query?

Answer

Taryn picture Taryn · Mar 1, 2013

You should be able to JOIN the tables on the profile.id and the profileid in the other tables.

If you are sure the profileid exists in all three tables, then you can use an INNER JOIN. The INNER JOIN returns matching rows in all of the tables:

select p.id,
  p.name,
  c.desc ContactDesc,
  a.desc AddressDesc
from profile p
inner join contact c
  on p.id = c.profileid
inner join address a
  on p.id = a.profileid
where p.name = 'bla'
  and c.ord = 1
  and a.ord = 1

If you are not sure that you will have matching rows, then you can use a LEFT JOIN:

select p.id,
  p.name,
  c.desc ContactDesc,
  a.desc AddressDesc
from profile p
left join contact c
  on p.id = c.profileid
  and c.ord = 1
left join address a
  on p.id = a.profileid
  and a.ord = 1
where p.name = 'bla'

If you need help learning JOIN syntax, here is a great visual explanation of joins