Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three way join in sql

Tags:

sql

sql-server

I have three tables titled "Guest", "Guest_Address" and "Acutal_Address". Guest_Address is a linking table between guest and acutal_address. This is what I have so far.

  SELECT GUEST_ADDRESS.ADDRESS_CODE,(GUEST_FNAME+' '+GUEST_LNAME) AS GUEST_NAMES
  FROM GUEST JOIN GUEST_ADDRESS 
  ON GUEST.ADDRESS_NUM = GUEST_ADDRESS.ADDRESS_NUM;

This only joins the Guest and Guest_address table, but I need to join Guest and Acutal_Address. Here is the ERD. enter image description here

like image 669
Naman Avatar asked Jun 24 '13 01:06

Naman


People also ask

Can you do 3 JOINs in SQL?

Using JOIN in SQL doesn't mean you can only join two tables. You can join 3, 4, or even more! The possibilities are limitless.

What are the 3 types of JOINs in SQL?

Different Types of SQL JOINs (INNER) JOIN : Returns records that have matching values in both tables. LEFT (OUTER) JOIN : Returns all records from the left table, and the matched records from the right table. RIGHT (OUTER) JOIN : Returns all records from the right table, and the matched records from the left table.

How do I join 3 tables inner join?

It is possible to use multiple join statements together to join more than one table at the same time. To do that you add a second INNER JOIN statement and a second ON statement to indicate the third table and the second relationship.


2 Answers

What you want to do is do an additional join to the actual_address table like so :

  SELECT GUEST_ADDRESS.ADDRESS_CODE,(GUEST_FNAME+' '+GUEST_LNAME) AS GUEST_NAMES
  FROM GUEST 
  JOIN GUEST_ADDRESS ON GUEST.ADDRESS_NUM = GUEST_ADDRESS.ADDRESS_NUM
  JOIN ACTUAL_ADDRESS ON GUEST_ADDRESS.ADDRESS_CODE = ACTUAL_ADDRESS.ADDRESS_CODE

Mind if I ask why you have that linking table? Can guests have multiple addresses? If that is the case I would change the join from GUEST_ADDRESS to GUEST based on GUEST_ID, rather than ADDRESS_NUM as using ADDRESS_NUM makes the relationship between the two tables a one-to-one relationship rather than one-to-many

Also worth noting that the query above will not return a record for the guest if there is no address in the ACTUAL_ADDRESS table or link in the GUEST_ADDRESS table due to the JOIN. If you want it to return guest details regardless of address you can simply change the JOIN to LEFT JOIN

like image 63
JanR Avatar answered Oct 30 '22 06:10

JanR


There is a many-to-many relationship between Guest and ActualAddress via the auxilary table GuestAddress. So to join then all together into one set do:

select * 
from Guest 
left join GuestAddress on GuestAddress.Guest_ID = Guest.Guest_ID 
left join ActualAddress on ActualAddress.AddressCode = GuestAddress.Address_Code

Then use the where clause to filter the set down to a smaller one (sub-set), if need be

like image 25
SyntaxGoonoo Avatar answered Oct 30 '22 08:10

SyntaxGoonoo