Using an offer with the Union

I have two tables, t1 and t2, with the same columns (id, desc) and data. But one of the desc columns may have different data for the same primary key, id.

I want to select all of these rows from these two tables so that t1.desc! = T2.desc

select a.id, b.desc 
FROM (SELECT * FROM t1 AS a
      UNION ALL 
      SELECT * FROM t2 AS b)
WHERE a.desc != b.desc

For example, if t1 has (1, 'aaa') and (2, 'bbb') and t2 has (1, 'aaa') and (2, 'bbb1'), then the new table should have (2, 'bbb' ) and (2, 'bbb1')

However, this does not work. Please let me know where I am going wrong and how to do it right.

+4
source share
3 answers

UNION ALL , . a b, .

, , , , t1 id, t2, . JOIN:

SELECT a.id, b.desc
FROM t1 AS a
JOIN t2 AS b ON a.id = b.id
WHERE a.desc != b.desc

t1 , t2, , .

, ,

UNION ALL , , , :

SELECT a.id, b.desc -- t1 is a, t2 is b
FROM t1 AS a
JOIN t2 AS b ON a.id = b.id
WHERE a.desc != b.desc
    UNION ALL
SELECT a.id, b.desc -- t1 is b, t2 is a
FROM t2 AS a
JOIN t1 AS b ON a.id = b.id
WHERE a.desc != b.desc
+2

Union . Join

SELECT * 
FROM t1 AS a 
inner join  t2 AS b
on a.id =b.id 
and a.desc != b.desc
+4

UNION SELECT.

Note that each SELECT statement in UNION must have the same number of columns. Columns must also have similar data types.

So, if it has the same number of columns and the same data type, then use Union, otherwise the connection can be used. It can be used.

SELECT * 
FROM t1 AS a 
inner join  t2 AS b
on a.id =b.id 
and a.desc != b.desc
+1
source

Source: https://habr.com/ru/post/1626474/


All Articles