试图优化sql查询

时间:2014-08-20 13:47:40

标签: sql sql-server tsql optimization

我有以下查询需要几秒钟才能运行:

 SELECT COUNT(*) cnt
   FROM [PTYCHRG] A, [AVAIL_ACTION_TYPE_CODES_TEMP] B
  WHERE TRIM(A.CASE_ID) = TRIM(caseid)
    AND TRIM(B.casecode) = TRIM(casecd)
    AND (
            TRIM(A.ACTN_CD) = TRIM(B.ACTIONCODE)
            OR TRIM(A.INDICTED_ACTN_CD) = TRIM(B.ACTIONCODE)
            OR TRIM(A.AMENDED_ACTN_CD) = TRIM(B.ACTIONCODE)
        )
    AND LOWER(TRIM(B.DOMAIN)) = LOWER(TRIM(domain))
    AND [rownum] = 1;

我正在寻找一种方法/方法来加速它,因为它是更大过程的一部分。

我基本上想看看是否至少有一条记录(我不关心我撤回哪个字段,我只想知道是否至少有一条记录)。

关于我能做些什么不同以使其运行得更快的任何想法?

2 个答案:

答案 0 :(得分:1)

这是用适当的join语法重写的查询,更好的表别名和更少的括号::

SELECT COUNT(*) cnt
FROM PTYCHRG p JOIN
     AVAIL_ACTION_TYPE_CODES_TEMP atc
     ON TRIM(p.CASE_ID) = TRIM(atc.caseid) AND
        TRIM(atc.casecode) = TRIM(p.casecd) AND
        TRIM(atc.ACTIONCODE) IN (TRIM(p.ACTN_CD), TRIM(p.INDICTED_ACTN_CD), TRIM(p.AMENDED_ACTN_CD)) AND
        LOWER(TRIM(atc.DOMAIN)) = LOWER(TRIM(p.domain)) AND
 WHERE rownum = 1;

这些都没有解决任何问题。相反,它们可以更容易地解决问题。首先,您正在运行值的函数。这通常会阻止SQL Server使用索引,甚至可以对连接做出更明智的决策。如果空间确实存在问题,则有两种解决方案:功能索引或修复数据。我会修复数据:

update PTYCHRG
    set Case_Id = TRIM(Case_id),
        ActionCode = TRIM(ActionCode),
        ACTN_CD = TRIM(ACTN_CD),
        INDICTED_ACTN_CD = TRIM(INDICTED_ACTN_CD),
        AMENDED_ACTN_CD = TRIM(AMENDED_ACTN_CD),
        domain = lower(trim(domain));

update AVAIL_ACTION_TYPE_CODES_TEMP
    set caseid = trim(caseid),
        casecode = trim(casecode)
        ACTIONCODE = trim(ACTIONCODE),
        domain = lower(trim(domain));

然后查询变为:

SELECT  COUNT(*) cnt
FROM PTYCHRG p JOIN
     AVAIL_ACTION_TYPE_CODES_TEMP atc
     ON p.CASE_ID = atc.caseid AND
        atc.casecode = p.casecd AND
        atc.ACTIONCODE IN (p.ACTN_CD, p.INDICTED_ACTN_CD, p.AMENDED_ACTN_CD) AND
        atc.DOMAIN = p.domain AND
 WHERE rownum = 1;

然后我会推荐索引。你可以尝试:

create index idx_AVAIL_ACTION_TYPE_CODES_TEMP_4
    on AVAIL_ACTION_TYPE_CODES_TEMP(caseid, casecode, domain, actioncode)

答案 1 :(得分:0)

赖安

您能看到,SQL是否与您的结果相同。

SELECT  COUNT(*) cnt
FROM    [PTYCHRG] A
JOIN    [AVAIL_ACTION_TYPE_CODES_TEMP] B
ON      TRIM(A.CASE_ID) = TRIM(caseid)
AND     ISNULL(TRIM(A.ACTN_CD),ISNULL(TRIM(A.INDICTED_ACTN_CD),TRIM(A.AMENDED_ACTN_CD))) = TRIM(B.ACTIONCODE)
WHERE   [rownum] = 1

如果可以避免,请从sql中删除TRIM()