[英]SQL Query Return All Results from Table A and Only Results from Table B that are not included in Table A
I am trying to query two tables and return a single result set that includes all values from table A and only values from Table B that are not included in Table A. 我正在尝试查询两个表并返回单个结果集,该结果集包含表A中的所有值,并且仅包含表B中不包含在表A中的值。
Table A Table B
ID Name ID Name
A John C Drew
B Jacob D Shane
C Nancy
Based on the ID column, result set should be: 根据ID列,结果集应为:
ID Name
A John
B Jacob
C Nancy
D Shane
I would exclude ID C from Table B from the result set because table A has a record with an ID of C. 我将从结果集中将ID C从表B中排除,因为表A的ID为C。
Does anyone know how I would begin to accomplish this? 有谁知道我将如何开始做到这一点?
You can do this as using union all
and not exists
: 您可以通过使用
union all
并且not exists
来完成此操作:
select a.id, a.name
from a
union all
select b.id, b.name
from b
where not exists (select 1 from a where a.id = b.id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.