Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to chain JOINs to query a distant table?

I am writing an app for home use and decided to use SQLite as the database to learn some SQL.

The app works as follows:

  • there is a set of people who have a name → this information comes from place A and is reflected in the people table.
  • I have from an unrelated source B some results (table results) that contain the result of an action and points to a "users reference" (also coming from B)
  • I manually linked the two worlds by pointing the source B users to the "people".

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I now would like to get a table of people.name who did not do the thing they were suppose to do (i.e. done for them is NULL).

This is the place where my previous amateur dev experience does not help anymore: how to connect the three tables so that I can SELECT from one table (SELECT name from people) but put a condition on a table that is two hops away.

I thought that OUTER JOIN would be a solution (and I still think it is) but I have one intermediate table. Basically I do not know how to "chain" joins.

How should I approach that?

>Solution :

Join two times:

SELECT name
 from people
 join app_user on (people.id = app_user.id_people)
 join results on (app_user.id_app = results.id_app and results.done is null)

Here we join table app_user to table people, and then join results to previous result.

There is no need for outer join, if table results contains row for not done tasks.

If table results doesn’t contain row for not done tasks, than you’ll need outer join with where clause.

SELECT name
 from people
 join app_user on (people.id = app_user.id_people)
 left join results on (app_user.id_app = results.id_app)
where results.done is null

Hope this helps with your confusion.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading