更高效的T-SQL语句

时间:2016-03-03 12:48:59

标签: tsql

美好的一天,

目前我们使用SQL作为我们的Solarwinds产品的数据库,我已经编写了一个下面的查询,我只想知道是否有更有效的方法来执行查询。

这里发生的是我们为正在监视的设备获取不同的值,如果条件已更改,则警告它似乎WHERE子句过度。

所以我想要的是如果AssignmentName = x并且currentvalue不是='y'值然后警告。

FROM 
CustomPollerStatus INNER JOIN CustomPollerAssignmentView ON              CustomPollerStatus.CustomPollerAssignmentID =   CustomPollerAssignmentView.CustomPollerAssignmentID  
LEFT OUTER JOIN CustomPollers ON CustomPollerAssignmentView.CustomPollerID =     CustomPollers.CustomPollerID 
LEFT OUTER JOIN Nodes ON CustomPollerAssignmentView.NodeID = Nodes.NodeID) 

where AssignmentName = 'a' and currentvalue != '24'
and AssignmentName = 'b' and currentvalue != '1'
and AssignmentName = 'c' and currentvalue != 'RUN'
and AssignmentName = 'd' and currentvalue != 'RUN'
and AssignmentName = 'e' and currentvalue != '72'
and AssignmentName = 'f' and currentvalue != '30'
and AssignmentName = 'g' and currentvalue != '72'
and AssignmentName = 'h' and currentvalue != '30'
and AssignmentName = 'i' and currentvalue != '276'
and AssignmentName = 'j' and currentvalue != '72'

我是TSQL的新手,任何知识在创建更有效的查询方面都会很棒

1 个答案:

答案 0 :(得分:2)

我猜你打算写

SELECT * 

FROM CustomPollerStatus 
    INNER JOIN CustomPollerAssignmentView ON CustomPollerStatus.CustomPollerAssignmentID = CustomPollerAssignmentView.CustomPollerAssignmentID  
    LEFT OUTER JOIN CustomPollers ON CustomPollerAssignmentView.CustomPollerID = CustomPollers.CustomPollerID 
    LEFT OUTER JOIN Nodes ON CustomPollerAssignmentView.NodeID = Nodes.NodeID) 

where (AssignmentName = 'a' and currentvalue != '24')
    OR (AssignmentName = 'b' and currentvalue != '1')
    OR (AssignmentName = 'c' and currentvalue != 'RUN')
    OR (AssignmentName = 'd' and currentvalue != 'RUN')
    OR (AssignmentName = 'e' and currentvalue != '72')
    OR (AssignmentName = 'f' and currentvalue != '30')
    OR (AssignmentName = 'g' and currentvalue != '72')
    OR (AssignmentName = 'h' and currentvalue != '30')
    OR (AssignmentName = 'i' and currentvalue != '276')
    OR (AssignmentName = 'j' and currentvalue != '72')

或者你的意思是

...
WHERE (AssignmentName IN  ('a','b', 'c', 'd', 'e', 'f','g', 'h','i','j')
    AND CurrentValue NOT IN ('24', '1','RUN','72','30''276')

无论哪种方式,查询都不会更有效。如果您遇到性能问题,我会查看您的索引。