这是表结构和示例数据
表datalinkinterface
nodeid | ifindex | nodeparentid | parentifindex
100000 | 3 | 100004 | 11
100001 | 3 | 100007 | 100
100002 | 5 | 100009 | 66
表节点
nodeid | nodesysname
100000 | ant
100001 |bird
100002 | cat
100004 | dog
100007 | egg
100009 | fish
表snmpinterface
nodeid | snmpifiname | snmpphysaddr | snmpifdescr | snmpifindex
100000 | 1/1/1 | 00:AA | AAA | 3
100001 | 1/1/2 | 00:BB | BBB | 3
100002 | 1/1/3 | 00:CC | CCC | 5
100004 | 2/1/1 | 00:DD | DDD | 11
100007 | 2/1/2 | 00:EE | EEE | 100
100009 | 2/1/3 | 00:FF | FFF | 66
table ipinterface
nodeid | ipaddr
100000 | 192.168.0.1 |3
100001 | 192.168.0.2 | 3
100002 | 192.168.0.3 |5
100004 | 192.168.0.4 |11
100007 | 192.168.0.5 |100
100009 | 192.168.0.6 |66
我想得到的是
nodeid | ifindex | nodeparentid | parentifindex
to
|srcnodesysname |srcsnmpifname | srcsnmpphyaddr | srcipaddr| srcsnmpifdescr |destnodesysname |destsnmpifname | destsnmpphyaddr | destipaddr| destsnmpifdescr |
(Ex.)
100000 | 3 | 100004 | 11
to
ant | 1/1/1 | 00:AA | 192.168.0.1 | AAA | dog | 2/1/1 | 00:DD | 192.168.0.4 | DDD
如何编写sql语句来查询以获得这样的结果。
答案 0 :(得分:1)
我假设您想要从节点返回结果并在同一查询中包含父节点?如果是这样,请使用JOIN
:
SELECT n.nodesysname, s.snmpifiname, s.snmpphysaddr, i.ipaddr, s.snmpifdescr ,
n2.nodesysname parentnodesysname, s2.snmpifiname parentsnmpifiname, s2.snmpphysaddr parentsnmpphysaddr, i2.ipaddr parentpaddr, s2.snmpifdescr parentsnmpifdescr
FROM Node n
JOIN datalinkinterface d ON n.nodeid = d.nodeid
JOIN snmpinterface s ON n.nodeid = s.nodeid
JOIN ipinterface i ON n.nodeid = i.nodeid
LEFT JOIN node n2 ON d.nodeparentid = n2.nodeid
LEFT JOIN snmpinterface s ON n2.nodeid = s2.nodeid
LEFT JOIN ipinterface i ON n2.nodeid = i2.nodeid
我已经使用LEFT JOIN
来获取父结果,以防父母不存在。