I have a database in which there are multiple posts. Each post can be associated with one or more location. Each location is then associated with one country.
This is handled through four tables:
- post (with the
idandpost_title) - postlocation (with the fields
post_idandlocation_id– to allow a one to many relationship) - location (with the fields
id,location_titleandcountry_id) - country (with the
fields,idandcountry_title)
I want to perform a simple, effective select to retrieve a list of posts and each one’s associated locations and each of those locations’ country.
I’m at a loss as to how to best achieve this, and any help would be most welcome. Thank you.
Use
LEFT JOIN:Here’s an explanation of how LEFT JOIN works: http://www.mysqltutorial.org/mysql-left-join.aspx
When you have multiple LEFT JOINs, then in each case it uses the cumulative results so far as the “left” table and the table your are joining on as the “right” table.
So the query above will return one row for every post/location/country. Note that this means there will be potentially several rows with the same
post.*data (one for eachpostlocationassociated with taht post).And if a post has no postlocations associated with it, that post will still show up in the results (but with null rows for
location.*andcountry.*). Similarly, if a location has no country associated it with it, the post/location rows will still show up in the output (but with null rows forcountry.*). This is the advantage of LEFT JOIN — you always get all the rows from the table on the “left”.