S
S
sashavol2018-12-12 20:09:51
MySQL
sashavol, 2018-12-12 20:09:51

How to get the same table twice with JOIN?

Good evening, I ran into another task with an sql query, which I decided to complicate and everything broke for me. I use Postgresql, but I don't think it matters.
I had the following query, where "car" contained the client_id column of the "client" table:

SELECT
                client.someone_field, 
                car.*
            FROM car
                INNER JOIN client ON client.id = car.client_id 
            WHERE 1=1 ';

The query is simple, it returns data from the data linked by id from the second table.
But you need to make one more binding with the same second table (client), but through the binding table, I figured it out like this:
SELECT
                client.someone_field, // данные от первой связки
                client_second.someone_field // данные от второй связки
                car.*
            FROM car
                INNER JOIN client ON client.id = car.client_id 
                INNER JOIN client_car ON client_car.car_id = car.id  // связывающая таблица которая имеет id одного поля и id другого поля (один к одному)
                INNER JOIN client client_second ON client_second.id = client_car.client_id // тут пытаюсь взять ID с противоположного столбика у связывающей таблицей и сравнить с таблицей client
            WHERE 1=1 ';

Actually, who has mastered, such request returns nothing. If this is translated into logic, then the first join is to get the owner of the current "car", the next 2 JOINs were meant to get the owner of the current "car".

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2018-12-12
@sashavol

Join is not entirely correct.
Try like this:

SELECT
                client.someone_field, // данные от первой связки
                client_second.someone_field // данные от второй связки
                car.*
            FROM car
                JOIN client ON client.id = car.client_id 
                JOIN client_car ON client_car.car_id = car.id 
                JOIN client_second ON client_second.id = client_car.client_id 
            WHERE 1=1;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question