Correct code to select and compare

Asked

Viewed 96 times

0

I want to select * from table A that are different from table B and have used the following code:

select * from Tabela A inner join Tabela B on A1 != B1 and A2 != B2 and A3 != B3

but the computer memory goes to the limit and blocks the PC.

Table A

ID  A1  A2  A3  A4  A5
1   1   2   3   4   XPTO1
2   2   3   4   5   XPTO2
3   3   4   5   6   XPTO3
4   4   5   6   7   XPTO4
5   5   6   7   8   XPTO5
6   6   7   8   9   XPTO6
7   7   8   9   10  XPTO7
8   8   9   10  11  XPTO8
9   9   10  11  12  XPTO9
10  10  11  12  13  XPTO10
11  11  12  13  14  XPTO11
12  12  13  14  15  XPTO12
13  13  14  15  16  XPTO13
14  14  15  16  17  XPTO14
15  15  16  17  18  XPTO15
16  16  17  18  19  XPTO16
17  17  18  19  20  XPTO17
18  18  19  20  21  XPTO18
19  19  20  21  22  XPTO19
20  20  21  22  23  XPTO20

Table B

ID  B1  B2  B3
1   1   2   3
2   5   6   7
3   9   10  11
4   13  14  15
5   17  18  19
  • You will find everything you need here : https://www.w3schools.com/sql/sql_distinct.asp

2 answers

1

Use the clause EXISTS

In the specific case of your example:

SELECT * FROM A
WHERE NOT EXISTS (
  SELECT * FROM B
  WHERE A1 = B1
  AND A2 = B2
  AND A3 = B3)

I created a DB Fiddle for you to see how it works and test if it is the result you expect.

1

You can do it like this:

SELECT a.*
FROM 'Tabela A' AS a
WHERE NOT EXISTS
(SELECT `b.ID`
 FROM 'Tabela B' AS b
 WHERE b.B1 = a.A1
 AND b.B2 = a.A2
 AND b.B3 = a.A3);

You make a sub-query that selects all items in table B that are equal to the items in Table A, if the row in Table A does not exist in the result of this sub-query, this row only exists in Table A.

Or so:

SELECT *
FROM 'Tabela A'
WHERE (A1, A2, A3) NOT IN
(SELECT B1, B2, B3
 FROM 'Tabela B');

This last one I saw now in this link, which has a third example with LEFT OUTER JOIN, that the article claims to be the most efficient, but I believe it does not suit you, because you need all fields of Table A:

Union, Difference, Intersection in Mysql
http://eccdb2014bk.blogspot.com.br/2014/03/union-difference-intersection-in-mysql.html

Browser other questions tagged

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