I have two tables with relation N-N:
ITEM_ORC ITEM_COMP
| OP | Item Orçado | | OP | NF | Item Comprado |
+-------+------------------+ +-------+---------+------------------+
| 1 | Lápis | | 1 | 101 | Lapis Preto |
| 1 | Borracha | | 1 | 102 | Caderno C Dura |
| 1 | Caderno | | 2 | 102 | Regua 15cm |
| 2 | Régua | | 2 | 102 | Lousa Verde |
| 2 | Lousa | | 2 | 103 | Caneta BIC Az |
I need a query that yields the following result:
Relação Orçamento X Compras
| OP | Item Orçado | NF | Item Comprado |
+------+-----------------+---------+--------------------+
| 1 | Lápis | 101 | Lapis Preto |
| 1 | Borracha | null | null |
| 1 | Caderno | 102 | Caderno C Dura |
| 2 | Régua | 102 | Regua 15cm |
| 2 | Lousa | 102 | Lousa Verde |
| 2 | null | 103 | Caneta BIC Az |
Since there is no relationship between items, a correct order between them is not required. I would just like the listing by OP, ie it could be that way the result, for example:
| OP | Item Orçado | NF | Item Comprado |
+------+-----------------+---------+--------------------+
| 1 | Lápis | 102 | Caderno C Dura |
| 1 | Borracha | null | null |
| 1 | Caderno | 101 | Lapis Preto |
| 2 | Régua | 102 | Lousa Verde |
| 2 | Lousa | 103 | Caneta BIC Az |
| 2 | null | 102 | Regua 15cm |
So far I've done the following query:
SELECT
b.OP
,Item Orçado
,NF
,Item Comprado
FROM
(SELECT
OP
,Item Orçado
FROM
ITEM_ORC) a
full join
(SELECT
OP
,NF
,Item Comprado
FROM
ITEM_COMP) b
ON a.OP = b.OP
But the result I get is that for each budgeted item I get each of the purchased ones:
| OP | Item Orçado | NF | Item Comprado |
+------+-----------------+---------+--------------------+
| 1 | Lápis | 101 | Lapis Preto |
| 1 | Lápis | 102 | Caderno C Dura |
| 1 | Borracha | 101 | Lapis Preto |
| 1 | Borracha | 102 | Caderno C Dura |
| 1 | Caderno | 101 | Lapis Preto |
| 1 | Caderno | 102 | Caderno C Dura |
| 2 | Régua | 102 | Regua 15cm |
| 2 | Régua | 102 | Lousa Verde |
| 2 | Régua | 103 | Caneta BIC Az |
| 2 | Lousa | 102 | Regua 15cm |
| 2 | Lousa | 102 | Lousa Verde |
| 2 | Lousa | 103 | Caneta BIC Az |
Just by pointing out, the only relationship between the tables is the OP. The items, despite coincidences, are unrelated.
Can you help me? Thanks!