优化SQL查询组成案例

时间:2018-03-06 10:28:39

标签: sql-server

查询需要大约3分钟来返回数据,如何优化以便花费更少的时间?

SELECT A.ID, M.Name, DC.Fun_Name, CODE,
CASE 
WHEN CS.ID = 1 THEN (SELECT data FROM AAA WHERE [AAA_CODE] = CODE)
WHEN CS.ID = 2 THEN (SELECT data FROM BBB WHERE [BBB_CODE] = CODE)          
WHEN CS.ID = 3 THEN (SELECT data FROM CCC WHERE [CCC_CODE] = CODE)
WHEN CS.ID = 4 THEN (SELECT data FROM DDD WHERE [DDD_CODE] = CODE)
WHEN CS.ID = 5 THEN (SELECT data FROM EEE WHERE [EEE_CODE] = CODE)
WHEN CS.ID = 6 THEN (SELECT data FROM FFF WHERE [FFF_CODE] = CODE)      
END AS FOO,

FROM Table_A A

INNER JOIN Table_M M ON A.M_ID = M.M_ID
INNER JOIN Table_DC DC ON A.D_ID = DC.D_ID
INNER JOIN Table_CS CS ON A.CS_ID = CS.CS_ID

WHERE M.M_ID  = 'HNO3' AND A.NAME = 'Vitamin' AND CS.C_NAME = 'issue' ORDER BY M.M_ID, A.NAME

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码吗?我们的想法是使用[data]获取[foo]列的INNER JOINS

CREATE TABLE #DataSource
(
     [ID] INT
    ,[Name] VARCHAR(32)
    ,[Fun_Name] VARCHAR(32)
    ,[CODE] VARCHAR(32)
    ,[CSID] INT
    ,[FOO] VARCHAR(32)
);

INSERT INTO #DataSource([ID], [Name], [Fun_Name], [CODE], [CSID])
SELECT A.ID, M.Name, DC.Fun_Name, CODE,CS.ID
FROM Table_A A
INNER JOIN Table_M M
    ON A.M_ID = M.M_ID
INNER JOIN Table_DC DC 
    ON A.D_ID = DC.D_ID
INNER JOIN Table_CS CS 
    ON A.CS_ID = CS.CS_ID
WHERE M.M_ID  = 'HNO3' 
    AND A.NAME = 'Vitamin' 
    AND CS.C_NAME = 'issue';

--- updates
UPDATE #DataSource
SET [FOO] = A.[Data]
FROM #DataSource DS
INNER JOIN AAA A
    ON DS.[CODE] = A.[AAA_CODE]
WHERE DS.[CSID] = 1;

.....


UPDATE #DataSource
SET [FOO] = F.[Data]
FROM #DataSource DS
INNER JOIN FFF F
    ON DS.[CODE] = A.[FFF_CODE]
WHERE DS.[CSID] = 6;

SELECT [ID], [Name], [Fun_Name], [CODE], [FOO]
FROM #DataSource;

DROP TABLE #DataSource;