MYSQL query for the below result

  Kiến thức lập trình

Every transaction in Table A has related transactions.
The related transactions are shown in Table B.
Table C has the corresponding type name.
Need to pull all transactions where Type Payment_GP does not exist.

For example transaction with ID 1 has Rel_ID D which is Payment_GP. So any related transactions for 1 should not be returned.

Table A

ID
1
2
A
B
C
D
E
F

Table B

ID  Rel_ID
1   A
1   B
1   C
1   D
2   E
2   F

Table C

ID  Type
A   Payment_Adv
B   Payment_Clr
c   Payment_A
D   Payment_GP
E   Payment_Adv
F   Payment_Clr

Expected Output:

ID  Rel_ID  Type
2   G   Payment_Adv
2   H   Payment_Clr

My query is not returning the output as expected.

SELECT A.id,
       B.Rel_ID,
       C.Type
FROM Table_A A
INNER JOIN Table_B B ON A.ID = B.ID
INNER JOIN Table_C C ON B.Rel_ID = C.ID
WHERE NOT EXISTS
    (SELECT 1
     FROM Table_C C1
     WHERE C1.ID = C.ID
       AND C1.Type IN ('Payment_Adv', 'Payment_Clr'))
;

LEAVE A COMMENT