Select separate data from two tables excluding repeated ones

Asked

Viewed 36 times

1

How could I select in two tables bringing the column data SKU of both tables even if the data of one table does not exist in the other table, also need to delete the repeated data.

These are the table data item_divergence inserir a descrição da imagem aqui

This is the table data item_inventarios inserir a descrição da imagem aqui

This is the expected result;

inserir a descrição da imagem aqui

I tried using SQL below but my query became too slow to query with many items;

SELECT (IVT.sku) as SKU
        FROM item_divergencia as IDV
        INNER JOIN item_inventarios as IVT on (IDV.id_inventario = IVT.id_inventario)
        WHERE IDV.id_inventario='252'
      UNION
        SELECT (IDV.sku) as SKU
        FROM item_divergencia as IDV
        INNER JOIN item_inventarios as IVT on (IDV.id_inventario = IVT.id_inventario)
        WHERE IDV.id_inventario='252'
        ORDER BY SKU

2 answers

1

I was able to solve with the following query:

There was no need to create a relationship between the two tables. I selected the two tables individually and then used UNION to join the data excluding the repeated.

That way it got very fast to bring the results.

SELECT (IVT.sku) as SKU FROM item_inventarios as IVT WHERE IVT.id_inventario='252' GROUP by SKU
UNION
SELECT (IDV.sku) as SKU FROM item_divergencia as IDV WHERE IDV.id_inventario='252' GROUP by SKU
ORDER BY SKU

0

For repeated data, it is already the concept of GROUP BY , here is explanation and great examples:https://www.w3schools.com/sql/sql_groupby.asp

in your SQL, to group everything by SKU, just use

GROUP BY SKU

at the end.

I hope I helped, good luck!

  • Perfect explanation. However using LEFT JOIN would not bring the desired result because in the two tables I have rows of the SKU column that exists in one and does not exist and vise and versa.

  • Thanks, I saw that Group By was helpful! I hope I helped

  • It was yes. It helped a lot. Thank you!

  • No reason, if it is possible to give the Thumbs up

  • I edited to leave only GROUP BY, which was really useful. Abs

Browser other questions tagged

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