Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL SELECT from three tables

Tags:

sql

join

select

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 ;)

like image 357
Kosso Avatar asked May 17 '11 14:05

Kosso


2 Answers

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
like image 90
CristiC Avatar answered Oct 06 '22 01:10

CristiC


SELECT m.id,m.content_id,m.from_user_id,m.to_user_id,m.timestamp,u.name,c.title
FROM Map_table m
INNER JOIN User_table u ON u.id = m.from_user_id
LEFT OUTER JOIN Content_table c ON c.id = m.content_id
WHERE m.to_user_id = 1
like image 22
Justin Wignall Avatar answered Oct 06 '22 01:10

Justin Wignall