获取位于A而非B的人员的结果,反之亦然[SQL Server]
我必须从表1中获得一个只有col1订阅或只有col2订阅的人员列表。表2用于参考。我有一个单独查找每个的查询,但是如何将输出放在一个查询中呢 注意:表2有更多的列,但是为了简单起见,我没有在这里添加它们。我需要从表2中得到所有细节获取位于A而非B的人员的结果,反之亦然[SQL Server],sql,sql-server,Sql,Sql Server,我必须从表1中获得一个只有col1订阅或只有col2订阅的人员列表。表2用于参考。我有一个单独查找每个的查询,但是如何将输出放在一个查询中呢 注意:表2有更多的列,但是为了简单起见,我没有在这里添加它们。我需要从表2中得到所有细节 --This will get people that have col1 and not col2 select * from table2 inner join table1 on col1 = table2.col1 where table2.col1 not
--This will get people that have col1 and not col2
select *
from table2
inner join table1 on col1 = table2.col1
where table2.col1 not in (select col2 from table1)
--This will get people that have col2 and not col1
select *
from table2
inner join table1 on col1 = table2.col1
where table2.col1 in (select col2 from table1)
那么,我如何将这两个查询的结果合并为一个呢?没有工会。因为我需要输出表有col1和col2,如果一个存在,另一个应该为null
| Table1 |
|---------------------|------------------|
| Col1 | Col2 |
|---------------------|------------------|
| A | F |
|---------------------|------------------|
| B | G |
|---------------------|------------------|
| C | H |
|---------------------|------------------|
| D | I |
|---------------------|------------------|
| E | J |
|---------------------|------------------|
| Table2 |
|---------------------|
| Col1 |
|---------------------|
| A |
|---------------------|
| B |
|---------------------|
| C |
|---------------------|
| D |
|---------------------|
| E |
|---------------------|
| F |
|---------------------|
| G |
|---------------------|
| H |
|---------------------|
| I |
|---------------------|
| J |
|---------------------|
连接表2两次,然后检查表1中的一个订阅列是否匹配:
SELECT
t1.Col1,
t1.Col2
FROM table1 t1
LEFT JOIN table2 a
ON t1.Col1 = a.Col1
LEFT JOIN table2 b
ON t1.Col2 = b.Col1
WHERE
(a.Col1 IS NOT NULL AND b.Col1 IS NULL) OR
(a.Col1 IS NULL AND b.Col1 IS NOT NULL)
连接表2两次,然后检查表1中的一个且仅一个订阅列是否匹配:
SELECT
t1.Col1,
t1.Col2
FROM table1 t1
LEFT JOIN table2 a
ON t1.Col1 = a.Col1
LEFT JOIN table2 b
ON t1.Col2 = b.Col1
WHERE
(a.Col1 IS NOT NULL AND b.Col1 IS NULL) OR
(a.Col1 IS NULL AND b.Col1 IS NOT NULL)
left join(左联接)如何?你说我需要输出表有col1和col2是什么意思?如果一个存在,另一个应该为空?left join(左联接)如何?你说我需要输出表有col1和col2,如果一个存在,另一个应该为空是什么意思?