0

Trying to combine two tables with different columns and rows

TABLE_1

|     id_product      | product_state_1  |
|---------------------|------------------|
|         106002      |        1         |
|         114000      |        0         |
|         106005      |        1         |
|         106004      |        1         |

TABLE_2

|     id_product      |  product_state_2 |
|---------------------|------------------|
|         106002      |        0         |
|         114000      |        1         |
|         106005      |        1         |
|         109005      |        1         |

Required result_table

|     id_product      |  product_state_1 | product_state_2  |
|---------------------|------------------|------------------|
|         106002      |        1         |   0              |
|         114000      |        0         |   1              |
|         106005      |        1         |   1              |
|         109005      |        NULL      |   1              |
|         106004      |        1         |   NULL           |

I tried the following code with the UNION 

SELECT * FROM TABLE_1 UNION SELECT * FROM TABLE_2;

but the following code does not give the required result.


anna
  • 17
  • 6

1 Answers1

0

Use LEFT and RIGHT JOIN along with UNION:

SELECT t1.id_product, t1.product_state_1, t2.product_state_2 
FROM TABLE_1 t1 
LEFT JOIN TABLE_2 t2
ON t1.id_product = t2.id_product
UNION
SELECT t2.id_product, t1.product_state_1, t2.product_state_2 
FROM TABLE_1 t1 
RIGHT JOIN TABLE_2 t2
ON t1.id_product = t2.id_product;

DB Fiddle

pcsutar
  • 1,715
  • 2
  • 9
  • 14