1

I have two tables...

tbl1
ClientNo        ApptID          Status
1234            1               121
1234            2               121
1235            1               121
1235            2               121


tbl2
ClientNo        Valid         
1234            17 

I'm looking to select all clients from tbl1 - where ApptID = 2, and there is no corresponding record in tbl2. So based on this data, 1234 has a record in tbl2, then no need to display it in end result.

I would love to see this as the end result:

ClientNo        ApptID          Status
1235            2               121
chrki
  • 6,143
  • 6
  • 35
  • 55
BobSki
  • 1,531
  • 2
  • 25
  • 61

4 Answers4

1

You can try the following query:

SELECT t1.*
FROM tbl1 AS t1
WHERE t1.ApptID = 2 AND  
      NOT EXISTS (SELECT 1
                  FROM tbl2 AS t2
                  WHERE t1.ClientNo = t2.ClientNo )
Giorgos Betsos
  • 71,379
  • 9
  • 63
  • 98
1

You need to compare the join field to NULL

SELECT t1.* FROM tbl1 t1
   LEFT JOIN tbl_2 t2
   ON t1.ClientNo = t2.ClientNo 
   WHERE t1.ApptID=2 AND t2.ClientNo IS NULL

Or use sub-query as below:

SELECT * FROM tbl1
   WHERE ApptID=2 AND ClientNo NOT IN (SELECT ClientNo FROM tbl_2)
MaxZoom
  • 7,619
  • 5
  • 28
  • 44
1

Please try the below answer:

SELECT * FROM TBL2 T2
RIGHT JOIN
(SELECT * FROM TBL1 WHERE ApptID = 2) TBL T1
ON T2.ClientNo = T1.ClientNo 
WHERE T2.ClientNo IS NOT NULL;
Biswabid
  • 1,378
  • 11
  • 26
0

This question was asked and answered a lot of times:

You need to join with a first condition matching and a second condition which specifies the failed match:

SELECT t1.ClientNo
  FROM tbl1 t1
  LEFT JOIN tbl2 t2 ON
    t1.ClientNo = t2.ClientNo
    AND t1.ClientNo IS NULL
Community
  • 1
  • 1
danieli
  • 11
  • 4