1
votes

I am new to Mysql

I got assigned a simple exercise which I cant get to work.

I am given two tables as follows:

 Table A             Table B
ID Values           ID  Values
A    1               B    10
B    2               F    11
C    3               G    12
D    4               H    13
E    5               I    14
F    6               J    15
G    7               K    16

An the question states to obtain in a single Query all IDs that are in table A and not in table B (A,C,D,E) as well as all IDs that are in Table B but not in table A (H,I,J,K)

Example of data needed:

Example of data needed

Im currently triyng to run this code but not get the result expected

SELECT Table_A.ID_A,Table_B.ID_B
FROM Table_A, Table_B
WHERE Table_A.ID_A NOT IN (SELECT Table_B.ID_B FROM Table_B) AND Table_B.ID_B NOT IN(SELECT Table_A.ID_A FROM Table_A);
1
Use a UNION of two queries. One for A not in B, the other for B not in A. - Barmar
I think You wanted to say EXCEPT on the subject header. Except function is not available in Mysql. - Ozan Sen

1 Answers

1
votes

Use separate subqueries for the IDs in A that aren't in B, and the IDs in A that aren't in A. Then combine them with UNION to get all the results in a single table.

SELECT a.ID
FROM Table_A AS a
LEFT JOIN Table_B AS b ON a.ID = b.ID
WHERE b.ID IS NULL

UNION ALL

SELECT b.ID
FROM Table_B AS b
LEFT JOIN Table_A AS a ON a.ID = b.ID
WHERE a.ID IS NULL