Left Join repeat tables

Asked

Viewed 62 times

1

I’m trying to assemble a select that has the result below:

inserir a descrição da imagem aqui

With select below I can show the null in just one column. How could I make it work for 20? I have from item_1 to item_20 and the description of the item is in the table of pieces, in occurrences have only his code.

SELECT P1.descricao desc1
FROM ocorrencias
LEFT JOIN pecas P1
ON P1.cod_peccin=ocorrencias.item_1 
WHERE ocorrencias.cod = 2

I tried that way with two columns, but it didn’t work:

SELECT P1.descricao desc1, P2.descricao desc2
FROM ocorrencias
LEFT JOIN pecas P1, pecas P2
ON P1.cod_peccin=ocorrencias.item_1, P2.cod_peccin=ocorrencias.item_2
WHERE ocorrencias.cod = 2

1 answer

2


To whom it may interest, I have decided as follows (here are 3 items):

SELECT P1.DESCRICAO AS desc1, P2.DESCRICAO AS desc2, P3.DESCRICAO AS desc3
FROM ocorrencias o LEFT JOIN
     pecas P1
     on P1.cod_peccin = o.item_1 LEFT JOIN
     pecas P2
     on P2.cod_peccin = o.item_2 LEFT JOIN
     pecas P3
     on P3.cod_peccin = o.item_3
where
     o.cod=2

Browser other questions tagged

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