Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres multiple joins

Tags:

postgresql

This is a postgres db. I am attempting to pull dog breed names (Cane Corso, Labrador, etc) from a breed table, to display based on the foreign keys located in an animal table. My issue is the animal table has two foreign keys to this single breed table, and I keep getting errors with my query. The first breed name will return based on a left join, but the second I cannot get the name to display as I already have a left join. Below is a simplified outline of what I am attempting to do:

breed table (ID, BreedName) animal table (ID, breedID, breed2ID)  SELECT animal.ID, breed.BreedName FROM animal LEFT JOIN breed ON animal.breedID=breed.ID WHERE animal.ID='7'; 

What I need to do is also get the BreedName to join for animal.breed2ID which I am failing miserably at. I could easily hard code the breed names and have it display in the application, but this is not conducive to changes, additions, or deletions of breed names in the database.

like image 247
user1137376 Avatar asked Jan 08 '12 18:01

user1137376


People also ask

How do I use multiple joins in PostgreSQL?

The most basic join type is a cross-join (or Cartesian product). In a cross join, PostgreSQL joins each row in the first table to each row in the second table to produce a result table. If you are joining against a third table, PostgreSQL joins each row in the intermediate result with each row in the third table.

Can we join 3 tables in PostgreSQL?

2) Using PostgreSQL INNER JOIN to join three tables And each payment is processed by one and only one staff.

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 you use more than one join?

Multiple joins can be described as a query containing joins of the same or different types used more than once, thus giving them the ability to combine multiple tables. For this article we will first create a database geeks and then create three tables in it and then run our queries on those tables. 8.


1 Answers

just do another join on that same table:

SELECT animal.ID, breed1.BreedName as BreedName1, breed2.BreadName as BreadName2  FROM animal     LEFT JOIN breed as breed1 ON animal.breedID=breed1.ID     LEFT JOIN breed as breed2 ON animal.breedID=breed2.ID  WHERE animal.ID='7'; 
like image 121
kingdaemon Avatar answered Sep 18 '22 10:09

kingdaemon