gpt4 book ai didi

sql - 如何优化我的查询?

转载 作者:行者123 更新时间:2023-12-03 17:19:00 26 4
gpt4 key购买 nike

我想计算向下和向上的接口(interface)数量,并编写这段代码,从两个表节点和接口(interface)中计算它们。此代码有效,但我想知道任何其他方式或优化此代码?计算它们的最佳方法是什么?

SELECT
q1.NodeName,
q1.Nup as up,
q2.ndown as down
FROM (
SELECT
Nodes.NodeID AS NodeID,
Interfaces.NodeID AS InterfaceID,
Nodes.Caption AS NodeName,
Interfaces.Status as Status,
Count(Nodes.Caption) as Nup
FROM
Nodes INNER JOIN Interfaces ON (Nodes.NodeID = Interfaces.NodeID)
WHERE
(
(
(Interfaces.Status = '2'))
)
GROUP BY Nodes.NodeID, Nodes.Caption, Interfaces.Status, Interfaces.NodeID
) AS q1
INNER JOIN (
SELECT
Interfaces.NodeID AS InterfaceID,
Nodes.Caption AS NodeName,
Interfaces.Status as Status,
Count(Nodes.Caption) as ndown
FROM
Nodes INNER JOIN Interfaces ON (Nodes.NodeID = Interfaces.NodeID)
WHERE
(
(
(Interfaces.Status = '1'))
)

GROUP BY Nodes.NodeID, Nodes.Caption, Interfaces.Status, Interfaces.NodeID

) AS q2

ON (q1.NodeID = q2.InterfaceID)
order by down Desc

最佳答案

您可以组合查询:

SELECT
Nodes.Caption AS NodeName,
Count(
CASE WHEN Interfaces.Status = '2'
THEN 1
ELSE NULL
END) as up,
Count(
CASE WHEN Interfaces.Status = '1'
THEN 1
ELSE NULL
END) as down
FROM Nodes
INNER JOIN Interfaces ON (Nodes.NodeID = Interfaces.NodeID)
WHERE Interfaces.Status IN('1', '2')
GROUP BY Nodes.NodeID, Nodes.Caption
order by 3 Desc

注意:在您的原始查询中,如果接口(interface)始终处于打开状态或始终处于关闭状态,则它不会显示在结果集中,因为您使用的是 INNER JOIN .

关于sql - 如何优化我的查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5198670/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com