Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL JOIN data from 3 tables

Tags:

postgresql

I'm new to PostgreSQL and trying to get a query written. I'm pretty sure it's easy for someone who knows what they are doing - I just don't! :)

Basically I have three tables. In the first, I store details about patients. In the second, I store a reference to each image of them. In the third, I store the link to the file path for the image. I didn't design the database, so I'm not sure why the image files table is separated, but it is.

What I want to be able to do is select data from the first table, joining in data from a second then third table so I end up with the name & file path in the result.

So the basic structure is:

Table 1:
person_id | name

Table 2:
person_id | image_id

Table 3:
image_id | `path filename`

What I want to do is in one query, grab the person's 'name' and the image 'path filename'.

I'm happy with a "template" style answer with the join I need. I don't need it to be written in actual code. (i.e. I'm thinking you can just write me an answer that says SELECT table1.name, table3.pathfilename FROM JOIN ... etc...).

like image 258
John Cleary Avatar asked Apr 03 '13 22:04

John Cleary


People also ask

Can we join 3 tables using JOINs?

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.

How do I join 4 tables in PostgreSQL?

If you'd like to combine data stored in multiple (more than two) tables, you should use the JOIN operator multiple times. First, you join two tables as you normally would (using JOIN , LEFT JOIN , RIGHT JOIN , or FULL JOIN , as appropriate).

How do I join 3 tables inner join?

The syntax for multiple joins: SELECT column_name1,column_name2,.. FROM table_name1 INNER JOIN table_name2 ON condition_1 INNER JOIN table_name3 ON condition_2 INNER JOIN table_name4 ON condition_3 . . . Note: While selecting only particular columns use table_name.


2 Answers

Something like:

select t1.name, t2.image_id, t3.path
from table1 t1 
inner join table2 t2 on t1.person_id = t2.person_id
inner join table3 t3 on t2.image_id=t3.image_id
like image 189
ozczecho Avatar answered Oct 02 '22 06:10

ozczecho


Maybe the following is what you are looking for:

SELECT name, pathfilename
  FROM table1
  NATURAL JOIN table2
  NATURAL JOIN table3
  WHERE name = 'John';
like image 22
Daniel Frey Avatar answered Oct 02 '22 05:10

Daniel Frey