JOIN 3 tables (LEFT JOIN)

Asked

Viewed 420 times

0

I have a question regarding the best way (concerning performance and execution) to make the following select... Initially I thought of using LEFT JOIN, but I came across some restrictions on its LEFT JOIN feature.

Having 3 following tables:

SERVICO
- S_ID
- S_CODIGO
- S_STATUS

ENTREGA
- E_ID
- E_CODIGO
- E_INFO
- D_FK_ID (FK com a tabela DIARIO, coluna D_ID)

DIARIO
- D_ID
- D_DATA

S_CODIGO (SERVICO table) and E_CODIGO (DELIVERY table) are unusual and S_CODIGO has more data and the DELIVERY Table belongs to a part of these CODES (for this reason I thought of LEFT JOIN).

SELECT 
    s.S_CODIGO AS CODIGO,
    s.S_STATUS AS STATUS,
    e.E_INFO AS INFORMACAO,
    d.D_DATA_INSERT AS DATA_CADASTRO
FROM
    SERVICO s
LEFT JOIN
    ENTREGA e
    ON e.E_CODIGO  = s.S_CODIGO

from this select I wanted to make one more Join to the DELIVERY Table (column D_FK_ID) with the DIARIO Table (D_ID) to fetch the column D_DATA_INSERT.

to return something like this:

CODIGO - STATUS      - INFORMACAO - DATA_CADASTRO
200    - CONCLUIDO   - DIURNO...  - 2018-11-05
201    - ANDAMENTO   - DIURNO...  - 2018-11-05
203    - CONCUIDO    - DIURNO...  - 2018-11-05
205    - CONCUIDO    - null       - null
210    - CONCUIDO    - null       - null

1 answer

1


Just include a new join and add the table "DIARIO":

SELECT 
    s.S_CODIGO AS CODIGO,
    s.S_STATUS AS STATUS,
    e.E_INFO AS INFORMACAO,
    d.D_DATA_INSERT AS DATA_CADASTRO
FROM
    SERVICO s
LEFT JOIN
    ENTREGA e
    ON e.E_CODIGO  = s.S_CODIGO
LEFT JOIN DIARIO d
    ON e.D_FK_ID = d.D_ID

Can add as many join are necessary. I copied your example and made a LEFT JOIN, but it could be any other kind of join.

Here another similar question: SQL JOIN multiple tables

Browser other questions tagged

You are not signed in. Login or sign up in order to post.