Skip to content
Advertisement

How to count distance between two lines in a SQL database?

Here is a sample of my database with 3 colums : class, year and student_name.

enter image description here

I search the “distance” in terms of common student between two given student. (Like in the famous game “6 degrees of Bacon”)

The goal is to calculate the distance between Momo Thary (2018) and Paul Biloux (2020). And the answer is 2 students : Momo Thary was in the same class than Jack Spiral. Jack Spiral was in the same class than Lucien Lake. And Lucien Lake was in the same class than Paul Biloux.

So we can “link” Momo Thary and Paul Biloux with 2 students.

I am using SQLite online. With the following code, it is possible to know the common player of Jack Spiral and Paul Biloux :

The output is Lucien Lake.

But if I use this script for Momo Thary and Paul Biloux, there is no output. In fact, is it required to use Jack Spiral and then Lucien Lake to make the link.

Is it possible to adapt the script, to first know the quickest link (if there are many possible link), and then to know what is the path in term of student ? May SQL be suited to do this type of code or another language would be more appropriate ?

Advertisement

Answer

You can use a recursive query :

The result is :

It is quite inefficient, because all the possible path are explored.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement