SQL Server查询需要将近3个小时

时间:2016-11-21 14:04:17

标签: sql-server tsql

以下是我的查询,检索结果需要2个多小时,我不知道为什么。这些表有20万条记录。

    INSERT INTO tempoutput12345 (tempitm, templitm, URRF_Configurator_Item) 
    SELECT DISTINCT 
        [KYKIT] 'IBITM', iblitm, 'CFG_ITEM' 
    FROM  
        [database].[production].[PRODDTA].[tableF3293] with (nolock)
    JOIN  
        [database].[production].[PRODDTA].[tablef4102] with (nolock) ON  
    kykit = ibitm 
    WHERE
        EXISTS (SELECT templitm FROM tempoutput12345 
                WHERE templitm = iblitm)
        AND IBMCU LIKE '%'+'5217194'
        AND 1 = 1

    UNION ALL 

    SELECT DISTINCT
        [KYITM] 'IBITM', iblitm, 'CFG_ITEM' 
    FROM     
        [database].[production].[PRODDTA].[tableF3293] with (nolock) 
    JOIN     
        [database].[production].[PRODDTA].[tablef4102] with (nolock) ON 
    kyitm = 

    ibitm 
    WHERE 
        EXISTS (SELECT templitm FROM tempoutput&jobid& 
                WHERE templitm = iblitm)
        AND IBMCU LIKE '%'+'5217194'
        AND 1 = 1

    UNION ALL 

    SELECT DISTINCT 
        [RDITM] 'IBITM', iblitm, 'CFG_ITEM' 
    FROM    
        [database].[production].[PRODDTA].[tableF3283] with (nolock)
    JOIN     
        [database].[production].[PRODDTA].[tablef4102] with (nolock) ON 
    rditm = ibitm 
    WHERE    
        EXISTS (SELECT templitm FROM tempoutput&jobid& 
                WHERE templitm = iblitm) 
        AND IBMCU LIKE '%'+'5217194'
        AND 1 = 1;

以上查询需要更长时间。请帮我解决这个问题

2 个答案:

答案 0 :(得分:0)

由于您使用的是相同的,这相当于 不确定它是否会更快

SELECT DISTINCT 
    [KYKIT] 'IBITM', iblitm, 'CFG_ITEM' 
FROM  
    [SRVGDYDHJSQL02].[JDE_PRODUCTION].[PRODDTA].[F3293] with (nolock)
JOIN  
    [SRVGDYDHJSQL02].[JDE_PRODUCTION].[PRODDTA].[f4102] with (nolock) 
       ON kykit = ibitm 
JOIN tempoutput12345 
       on templitm = iblitm
WHERE IBMCU LIKE '%5217194'

答案 1 :(得分:0)

如果您使用SARG,它会很快。如果没有办法使用SARG只使用一次表扫描。你的qry没有优化。

select distinct b.*
from (select * from f4102 where IBMCU  LIKE '%5217194') ib,
(
    select [RDITM] 'IBITM', iblitm, 'CFG_ITEM' from [f4102]
    union all
    select [KYKIT] 'IBITM', iblitm, 'CFG_ITEM' from [f4102]
    union all
    select [kyitm] 'IBITM', iblitm, 'CFG_ITEM' from [f4102]) b
where ib.ibitm = b.IBITM

如果缺少,请在IBMCU.ibitm,f4102.RDITM,f4102.kyitm,f4102.KYKIT上使用索引。

不要在任何地方使用nolock - 它是可怜的。如果必要的话,仅使用它作为选项,只在一个地方使用(nolock)。