[英]How to select unique entries
我有一个网络设备接口表(link_id 指向 id):
id |device |interface |link_id
1 |switch1 |Gi1/1 |2
2 |switch2 |Gi1/1 |1
...
我的目标是拥有以下连接矩阵:
device_a |interface_a |device_b |interface_b
switch1 |Gi1/1 |switch2 |Gi1/1
我认为我可以得到:
SELECT a.device, a.interface, b.device, b.interface
FROM `links` a
INNER JOIN `links` b ON a.id = b.link_id
但结果我也得到了一个“反向”记录:
device_a |interface_a |device_b |interface_b
switch1 |Gi1/1 |switch2 |Gi1/1
switch2 |Gi1/1 |switch1 |Gi1/1
我怎样才能 select 只有唯一的条目? 有没有更聪明的方法来完成这项任务? (不同的表结构可能)
如果您将您的link_id
列移动到一个新表以关联id
和link_id
(下面重命名为id_a
和id_b
),则使用 2 个 JOIN 的查询变得简单。 这种表结构还可以规范化您的数据,因为现在 2 个接口之间的关系存储在单独的多对多表中,而不是作为interface
表中的附加 ID。
CREATE TABLE interfaces (
`id` INTEGER,
`device` VARCHAR(7),
`interface` VARCHAR(5)
);
INSERT INTO interfaces
(`id`, `device`, `interface`)
VALUES
('1', 'switch1', 'Gi1/1'),
('2', 'switch2', 'Gi1/1');
CREATE TABLE links (
`id_a` INTEGER,
`id_b` INTEGER
);
INSERT INTO links
(`id_a`, `id_b`)
VALUES
('1', '2');
SELECT
i.device as device_a,
i.interface interface_a,
i2.device as device_b,
i2.interface as inteface_b
FROM
links l
JOIN interfaces i ON i.id = l.id_a
JOIN interfaces i2 ON i2.id = l.id_b;
device_a | 接口_a | 设备_b | 接口_b |
---|---|---|---|
开关1 | Gi1/1 | 开关2 | Gi1/1 |
添加这样的条件:
SELECT a.device, a.interface, b.device, b.interface
FROM `links` a
INNER JOIN `links` b
ON a.id = b.link_id
AND a.id < a.link_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.