这是我的表格的简化版本
Name Vlan
Switch 1 1
Switch 1 2
Switch 1 3
Switch 2 1
Switch 2 2
我想将属于交换机1的所有vlan与属于交换机2的所有vlan进行比较,并使用SQL查询在其中一个交换机中打印出丢失的vlans。有可能这样做吗?请注意,所有数据都位于同一个表中。
在上面提供的示例数据中,查询应该返回第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%')
答案 0 :(得分:3)
这将为您提供您所追求的目标。它没有对数据做出任何假设,并会给出所有缺失的记录。如果您想将其限制为仅限于“切换1”和“切换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)
答案 1 :(得分:3)
使用MS SQL Server。在 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)
答案 2 :(得分: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
答案 3 :(得分:1)
SELECT *
FROM yourTable
WHERE [Name] = 'Switch1'
AND [Vlan] NOT IN(SELECT [Vlan] FROM yourTable WHERE [Name] = 'Switch2')
Name Vlan
Switch1 3