2

这是我的表格的简化版本

Name      Vlan
Switch 1    1
Switch 1    2
Switch 1    3
Switch 2    1
Switch 2    2

我想将属于交换机 1 的所有 vlan 与属于交换机 2 的所有 vlan 进行比较,并使用 SQL 查询打印出其中一个交换机中缺少的那些。有可能这样做吗?请注意,所有数据都位于同一个表中。

在上面提供的示例数据中,查询应返回第 3 行

Switch 1,  3

这是我之前尝试过的查询(我的要求比我的查询中的简化版本多一些条件):

Select Vlans.VLANID From VLANS
 JOIN Nodes ON 
VLANS.NodeId = Nodes.NodeID
Where Nodes.sysName LIKE 'SSW010%' and Vlans.VlanID NOT In
(Select Vlans.VLANID AS Vlan2 From VLANS
 JOIN Nodes ON 
VLANS.NodeId = Nodes.NodeID
Where Nodes.sysName LIKE 'SSW001%')
4

4 回答 4

3

使用 MS SQL 服务器。在SQL Fiddle上检查此工作代码

SELECT T1.Name, T1.Vlan
  FROM yourTable T1
 WHERE NOT EXISTS (SELECT 1 
                     FROM yourTable T2
                    WHERE T2.Vlan = T1.Vlan
                      AND T2.Name <> T1.Name)
于 2012-09-18T07:29:21.017 回答
3

这会给你你所追求的。它不对数据做任何假设,并且会给出所有缺失的记录。如果您想将其限制为“Switch 1”,请将其添加到 WHERE 子句中。

SELECT
  t1.Name,
  t1.Vlan
FROM t t1
WHERE NOT EXISTS (SELECT 1 
                    FROM t t2
                   WHERE t2.Name <> t1.Name
                     AND t2.Vlan = t1.Vlan)

CREATE TABLE t 
(
  Name VARCHAR(10),
  Vlan INT
)


INSERT INTO t VALUES('Switch 1',1)   
INSERT INTO t VALUES('Switch 1', 2)
INSERT INTO t VALUES('Switch 1', 3)
INSERT INTO t VALUES('Switch 2', 1)
INSERT INTO t VALUES('Switch 2', 2)
于 2012-09-18T07:23:06.867 回答
1

这应该有效。

select 
  t1.Name
  ,t1.Vlan
from table t1
left join table t2 
  on t1.Vlan = t2.Vlan 
 and t1.Name='Switch 1' 
 and t2.Name = 'Switch 2'
where  t2.Name is null
union
select 
  t1.Name
  ,t1.Vlan
from table t1
left join table t2 
  on t1.Vlan = t2.Vlan 
 and t1.Name='Switch 2' 
 and t2.Name = 'Switch 1'
where  t2.Name is null
于 2012-09-18T07:18:07.597 回答
1
SELECT * 
FROM yourTable 
WHERE [Name] = 'Switch1'
AND [Vlan] NOT IN(SELECT [Vlan] FROM yourTable WHERE [Name] = 'Switch2')


Name    Vlan
Switch1 3
于 2012-09-18T07:49:04.127 回答