简体   繁体   中英

Bringing records in TableA Not in Table B Left Outer Join

The below question was asked in interview to me. I don't know whether its possible or not to use left outer join in this case

CREATE TABLE TableA(Id INT, Name VARCHAR(255));
CREATE TABLE TableB(Id INT);

INSERT INTO TableA(Id, Name)
VALUES (1, 'Person A'),
       (2, 'Person B'),
       (3, 'Person C'),
       (4, 'Person D'),
       (5, 'Person E'),
       (6, 'Person F');

INSERT INTO TableB(Id)
VALUES (1),
       (2),
       (3);

The output should be

Name
Person D
Person E
Person F

Two Table. TableA and Table B. I want the Names in Table A which are not in Table B. Is it Possible to do this by Left outer Join. With paper and pen I struggled for few minutes and I wrote a query in paper which I found wrong later.

Note: Please don't use Sub query. I did the same and the interviewer asked me to do that by left outer join.

Let me know whether its possible are not.

SQL Fiddle

Sounds easy enough

SELECT * FROM TableA a
LEFT JOIN TableB b on b.Id=a.Id
WHERE b.ID is null

That should give you the matches in table. The trick is to realize that you're interested in the null rows on the B side.

You may use Subquery ?

SELECT Name FROM TableA 
WHERE TableA.ID not in (SELECT TableB.ID From TableB)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM