Kosso Kosso - 13 days ago 10
SQL Question

SQL SELECT from three tables

I have three tables:

Map_table
- id
- content_id
- from_user_id
- to_user_id
- timestamp

User_table
- id
- name

Content_table
- id
- title


eg: I want to select rows from the Map_table where Map_table.to_user_id = 1

and also provide the User_table.name where Map_table.from_user_id = User_table.id

and also provide the Content_table.title where Map_table.content_id = Content_table.id

Map_table.content_id might be null and therefore not map to the Content_table

If been through a load of answers here and still tearing my hair out to get the results I need.
Can any SQL gurus out there see a simple solution. The potential JOINs required are frying my brain.

Any help would be much appreciated. For the sake of my scalp, among other things ;)

Answer
SELECT mt.*, ut.name, ct.title
FROM
     Map_table mt
INNER JOIN
     User_table ut on mt.from_user_id = ut.id
LEFT JOIN 
     Content_table ct on mt.content_id = ct.id
WHERE 
     mt.to_user_id = 1
Comments