结合两个简单的SQL Server查询需要很长时间

时间:2018-11-16 14:08:44

标签: sql-server ogc

我有两个简单的查询,它们在单独运行时会在预期的时间内执行。 第一个查询:

SELECT OBJECTID AS OID FROM PST_35053_SNAPPED;

花费不到一秒钟的时间,并返回大约3000行。 第二个查询:

SELECT DISTINCT PST.OBJECTID as OID FROM PST_35053_SNAPPED 
PST INNER JOIN  POWNERS_35053 POW
ON geometry::STGeomFromText('POINT(' + convert(varchar(16),POW.x) + ' ' +
convert(varchar(17),POW.y) + ')', 2100).STWithin(PST.Shape)=1;

花一秒钟返回大约2500行。

当将它们与EXCEPT组合以检索polygon IDs而没有点落入它们(大约500行)时,执行的查询将花费超过两分钟的时间(大约122秒):

SELECT OBJECTID AS OID FROM PST_35053_SNAPPED
EXCEPT
SELECT DISTINCT PST.OBJECTID as OID FROM PST_35053_SNAPPED 
PST INNER JOIN  POWNERS_35053 POW
ON geometry::STGeomFromText('POINT(' + convert(varchar(16),POW.x) + ' ' +
convert(varchar(17),POW.y) + ')', 2100).STWithin(PST.Shape)=1

有什么我想念的东西或做错了吗? 我正在使用 SQL Server 2012 SP3

2 个答案:

答案 0 :(得分:1)

尝试将您的脚本插入到临时表中,而不要对其进行组合。我们没有执行计划,只能向您展示以不同角度执行查询。 :

SELECT DISTINCT PST.OBJECTID as OID INTO #Temp FROM PST_35053_SNAPPED 
PST INNER JOIN  POWNERS_35053 POW
ON geometry::STGeomFromText('POINT(' + convert(varchar(16),POW.x) + ' ' +
convert(varchar(17),POW.y) + ')', 2100).STWithin(PST.Shape)=1;

SELECT OBJECTID AS OID FROM PST_35053_SNAPPED
EXCEPT
SELECT OID FROM #Temp;

或尝试不存在:

SELECT OBJECTID AS OID 
FROM PST_35053_SNAPPED PST1
WHERE NOT EXISTS 
    (SELECT 1 FROM 
        (
            SELECT DISTINCT PST.OBJECTID as OID FROM PST_35053_SNAPPED 
            PST INNER JOIN  POWNERS_35053 POW
            ON geometry::STGeomFromText('POINT(' + convert(varchar(16),POW.x) + ' ' +
            convert(varchar(17),POW.y) + ')', 2100).STWithin(PST.Shape)=1
        ) PST2
        WHERE PST1.OBJECTID=PST2.OBJECTID
    )

或尝试使用:

WITH Cte AS 
(
    SELECT DISTINCT PST.OBJECTID as OID FROM PST_35053_SNAPPED 
    PST INNER JOIN  POWNERS_35053 POW
    ON geometry::STGeomFromText('POINT(' + convert(varchar(16),POW.x) + ' ' +
    convert(varchar(17),POW.y) + ')', 2100).STWithin(PST.Shape)=1
)
SELECT OBJECTID AS OID FROM PST_35053_SNAPPED
EXCEPT
SELECT OID FROM Cte;

答案 1 :(得分:0)

没有查询执行计划很难说。 但是,如果我理解正确,下面的查询应该会得到相同的结果,并且会更快。

38
42
26