0

I have 2 table (A and B). Each row on table A have up to 3 correspondence on table B. Table B have a status field that can be either "x" "y" or "null".

I want to get all row from table A where no matching row from table B have the "X" status (see below picture). So basically I want row with Id 2 and 3.

enter image description here

Note, my from statement MUST BE on Table A.

So far I tried without success the following :

select *
from table A
left join table B on a.Id = b.ref
where status = 'Y'
or status is null;

select *
from table A
right join table B on a.Id = b.ref
where status = 'Y'
or status is null;

problem is that for every row from table A, I have a row in table B that satisfy the where condition so I get all 3 row returned instead of only the one in green. I need to do something like "having all matching row from table B != "X"

Yannick Richard
  • 1,219
  • 15
  • 25
  • You could find all the TableA records that have an X then select again subtracting those. Select * from TableA where id not in (select id from tableA left join TableB on a.id = b.id and status = 'x'); – Daniel Gale Mar 13 '18 at 18:08

2 Answers2

2

The idea is you try to match the row in table A with anyone on table B but only those with x on it.

If you cant you will get NULL and those are the rows you want.

 SELECT A.*
 FROM TableA as A
 LEFT JOIN TableB as B
   ON A.id = B.Ref
  AND B.status = 'x'
 WHERE B.status is null
Juan Carlos Oropeza
  • 47,252
  • 12
  • 78
  • 118
  • @DanielGale Nope, you are getting the ones doesnt matching any table B – Juan Carlos Oropeza Mar 13 '18 at 18:19
  • I tried in mysql and it worked perfectly. So basically, you are joining on b.status = 'x' which will return only one record from table B. then checking for null on right side which is totally working and brilliant. thanks for the answer. didnt knew we could have 2 conditions on the jointure. – Yannick Richard Mar 13 '18 at 18:31
  • Your JOIN condition can be as complex as you want. Remember accept the answer if solve the problem – Juan Carlos Oropeza Mar 13 '18 at 18:35
1
Select A.* 
from A 
where A.Id not in (select ref 
                   from B 
                   where B.ref = A.Id 
                     and B.Status = 'X')
Juan Carlos Oropeza
  • 47,252
  • 12
  • 78
  • 118
Hussein Salman
  • 7,806
  • 15
  • 60
  • 98