2

I am new in mysql.

I have two completely identical mysql tables (they have similar id).

Table_1

+----+------------+------+
| id | group_name | cell |
+----+------------+------+
|  1 | YE-04      | 12   |
|  2 | AG-11      | -200 |
|  3 | VG-17      | 11   |
+----+------------+------+

Table_2

+----+------------+------+
| id | group_name | cell |
+----+------------+------+
|  1 | YE-04      | NULL |
|  2 | AG-10      | 13   |
|  3 | VG-17      | 11   |
+----+------------+------+

And I would like to.

First, compare the columns (parameters) to the fact of their inconsistencies between themselves.

Second, group them by ID.

Third, output to the third (new) table in this form (display only those parameters that do not correspond to each other):

+----+------------+----------------|----------------+
| id | col_name   | table_1_param  |  table_2_param |
+----+------------+----------------+----------------+
|  1 | cell       | 12             | NULL           |
|  2 | group_name | AG-11          | AG-10          |
|  2 | cell       | -200           | 13             |
+----+------------+----------------+----------------+

I tried to group them using the JOIN and UNION commands, but it did not work for me.

D-Shih
  • 44,943
  • 6
  • 31
  • 51
David Grigoryev
  • 125
  • 1
  • 11

2 Answers2

1

You can unpivot using union all and then aggregate:

select id, col, max(val1) as val1, max(val2) as val2
from ((select id, 'group_name' as col, group_name as val1, null as val2
       from table1
      ) union all
      (select id, 'cell' as col, cell as val1, null as val2
       from table1
      ) union all
      (select id, 'group_name' as col, null as val1, group_name as val2
       from table2
      ) union all
      (select id, 'cell' as col, null as val1, cell as val2
       from table2
      ) 
     ) t
group by id, col
having not max(val1) <=> max(val2);
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

You can try below SQL to get job done:

SELECT t1.id, t1.group_name, t1.cell AS "table_1_param", t2.cell AS "table_2_param"
FROM Table_1 t1, Table_2 t2'
WHERE t1.id = t2.id
AND t1.cell != t2.cell
Geee
  • 2,217
  • 15
  • 30