从表中返回它们尚未在另一个表中使用的记录,3个表

时间:2016-10-04 17:57:11

标签: sql sql-server

我需要从NetworkDomain返回所有记录,其中任何这些网络尚未分配给特定组织(在本例中为OrgName1)。因此,在下面的示例中,如果我想返回尚未分配给OrgName1的所有网络(结果应该是NetName2和NetName3),我该怎么做? 注意:我需要订购网络ASC

表名=" BusinessOrganizationDomain"

|---------------------|------------------|
|        OrgUUID      |      OrgName     |
|---------------------|------------------|
|          1111       |      OrgName1    |
|---------------------|------------------|
|          2222       |      OrgName2    |
|---------------------|------------------|

表名=" BusinessOrganizationAuthorizedNetwork"

|        OrgUUID      |      NetUUID     |
|---------------------|------------------|
|          1111       |      5555        |
|---------------------|------------------|
|          2222       |      6666        |
|---------------------|------------------|

表名=" NetworkDomain"

|        NetUUID      |      NetName     |
|---------------------|------------------|
|          5555       |      NetName1    |
|---------------------|------------------|
|          6666       |      NetName2    |
|---------------------|------------------|
|          7777       |      NetName3    |
|---------------------|------------------|

3 个答案:

答案 0 :(得分:1)

一种方法是NOT EXISTS谓词

SELECT * FROM NetworkDomain nd
WHERE NOT EXISTS (
  SELECT 1 
  FROM BusinessOrganizationAuthorizedNetwork bn 
  INNER JOIN BusinessOrganizationDomain bd 
     ON bd.OrgUUID = bn.orgUUID AND bn.NetUUID = nd.NetUUID AND bd.OrgName = 'OrgName1'
)

答案 1 :(得分:0)

试试这个。不确定您是否尝试根据名称或ID选择组织,所以这两者都是。

按名称:

SELECT DISTINCT nd.* FROM NetworkDomain nd
LEFT JOIN BusinessOrganizationAuthorizedNetwork boan ON boan.NetUUID = nd.NetUUID
LEFT JOIN BusinessOrganizationDomain bod ON bod.OrgUUID = boan.OrgUUID
WHERE bod.OrgName IS NULL
ORDER BY nd.NetName

答案 2 :(得分:0)

试试这个,它会有所帮助。

按网名排序

select nd.NetName 
from
BusinessOrganizationDomain bod inner join 
BusinessOrganizationAuthorizedNetwork boan 
on boan.OrgUUID = bod.OrgUUID
inner join 
NetworkDomain nd
on nd.NetUUID != boan.NetUUID
where bod.OrgName='OrgName1'
ORDER by nd.NetName

按NetUUID排序

select nd.NetName 
from
BusinessOrganizationDomain bod inner join 
BusinessOrganizationAuthorizedNetwork boan 
on boan.OrgUUID = bod.OrgUUID
inner join 
NetworkDomain nd
on nd.NetUUID != boan.NetUUID
where bod.OrgName='OrgName1'
ORDER by nd.NetUUID