如何优化SQL查询

时间:2014-05-08 14:55:24

标签: sql sql-server tsql query-optimization

此查询需要3秒才能执行,但如果删除“convert”子句,则会立即执行,反之亦然。有人可以帮忙吗?

SELECT DISTINCT 
   N.ID, Groups.IP_Access
FROM         
   Name AS N 
INNER JOIN
   Activity AS A ON N.ID = A.ID 
INNER JOIN
   Groups ON N.ID = Groups.ID
WHERE     
   ((A.ACTIVITY_TYPE = 'LICENCE') AND 
    (A.PRODUCT_CODE = 'IP') AND 
    (A.THRU_DATE IS NULL) AND 
    (A.SOURCE_CODE = 'ICAS') AND 
    (N.MEMBER_TYPE IN ('MM', 'PM','ST', 'SC', 'SE', 'CA', 'CM', 'AC', 'IN', 'BC', 'NM', 'IS', 'RN', 'WEB','PS', 'PP', 'NP')) AND 
    (N.STATUS IN ('A', 'P')) AND 
    (N.ID <> 1) OR 
    CONVERT(bit, ISNULL(Groups.IP_access, 0)) = 1)  

1 个答案:

答案 0 :(得分:1)

这只是一种预感,因为很难说出你希望提取哪种数据,但是你可能会错过OR子句的一些括号。有关详细信息,请参阅https://stackoverflow.com/a/1241158/1445356

您的查询目前有这个有效的WHERE子句:

WHERE
(
    A.ACTIVITY_TYPE = 'LICENCE'
    AND A.PRODUCT_CODE = 'IP'
    AND A.THRU_DATE IS NULL
    AND A.SOURCE_CODE = 'ICAS'
    AND N.MEMBER_TYPE IN ('MM','PM','ST','SC','SE','CA','CM','AC','IN','BC','NM','IS','RN','WEB','PS','PP','NP')
    AND N.STATUS IN ('A','P')
    AND N.ID <> 1
)
OR Groups.IP_access = 1

是正确的逻辑吗?或者你想要这样做:

WHERE
    A.ACTIVITY_TYPE = 'LICENCE'
    AND A.PRODUCT_CODE = 'IP'
    AND A.THRU_DATE IS NULL
    AND A.SOURCE_CODE = 'ICAS'
    AND N.MEMBER_TYPE IN ('MM','PM','ST','SC','SE','CA','CM','AC','IN','BC','NM','IS','RN','WEB','PS','PP','NP')
    AND N.STATUS IN ('A','P')
    AND (
        N.ID <> 1
        OR Groups.IP_access = 1
    )