简体   繁体   English

将记录带入表A,而不带入表B左外部联接

[英]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. 表A和表B。我希望表A中的名称不在表B中。通过左外部联接可以做到这一点。 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. 注意:请勿使用Sub查询。 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 SQL小提琴

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. 诀窍是要意识到您对B侧的空行感兴趣。

You may use Subquery ? 您可以使用Subquery吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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