是否有可能优化这个ms sql查询?

时间:2014-11-10 09:23:13

标签: sql sql-server

此查询很小但是我的Access FrontEnd / SQL BackEnd应用程序停止运行速度变慢。 有没有办法优化它?

据我所知,它显示了最后一个CultureStepID的CID和WeekNr。

SELECT DISTINCT Culture.CID,
(SELECT TOP (1) WeekNr
FROM CultureStep
WHERE (CultureID = Culture.CID)
ORDER BY CultureStepID) AS normalstartweek

FROM Culture
INNER JOIN CultureStep ON Culture.CID= CultureStep.CID

编辑:

查询行数:2309

CultureStep表:13961

文化表:2472

enter image description here

2 个答案:

答案 0 :(得分:1)

试试这个:

第一种解决方案(您通过CultureStep的存在显示所有文化独立):

SELECT Culture.CID,
(SELECT CS.WeekNr
FROM CultureStep CS
WHERE (CS.CultureID = Culture.CID)
AND NOT EXISTS(
    SELECT 'NEXT'
    FROM CultureStep CS2
    WHERE CS2.CultureID = CS.CultureID
    AND CS2.CultureStepID > CS.CultureStepID)
) AS normalstartweek
FROM Culture

第二个解决方案:(如果存在链接的CultureStep,则显示所有文化):

SELECT Culture.CID,
(SELECT CS.WeekNr
FROM CultureStep CS
WHERE (CS.CultureID = Culture.CID)
AND NOT EXISTS(
    SELECT 'NEXT'
    FROM CultureStep CS2
    WHERE CS2.CultureID = CS.CultureID
    AND CS2.CultureStepID > CS.CultureStepID)
) AS normalstartweek
FROM Culture
WHERE EXISTS(
    SELECT 'CultureStep'
    FROM CultureStep
    WHERE (CultureID = Culture.CID)
)

答案 1 :(得分:1)

SELECT DISTINCT Culture.CID,
(SELECT TOP (1) WeekNr
FROM CultureStep
WHERE (CultureID = Culture.CID)
ORDER BY CultureStepID) AS normalstartweek
FROM Culture
WHERE Exists(SELECT CID FROM CultureStep WHERE CultureStep.CID=Culture.CID)