0

我有这个查询的性能问题。如果我删除状态列,它会运行得非常快,但是在列部分添加子查询会使查询延迟太多 1.02 分钟。如何修改此查询,使其快速运行以获取所需的数据。

我把那个子查询放在那里的原因是因为我需要最新活动的状态,一些活动的状态为空,所以我必须忽略它们。

机构:6.5k 行 - EstablishmentActivities:70k 行 - 状态:2(活动,非活动)

SELECT DISTINCT
    est.id,
    est.trackingNumber,
    est.NAME AS 'establishment',
    actTypes.NAME AS 'activity',
    (
        SELECT stat3.NAME
        FROM SACPAN_EstablishmentActivities eact3
        INNER JOIN SACPAN_ActivityTypes at3
            ON eact3.activityType_FK = at3.code
        INNER JOIN SACPAN_Status stat3
            ON stat3.id = at3.status_FK
        WHERE eact3.establishment_FK = est.id
          AND eact3.rowCreatedDT = (
            SELECT MAX(est4.rowCreatedDT)
            FROM SACPAN_EstablishmentActivities est4
            INNER JOIN SACPAN_ActivityTypes at4
                ON est4.establishment_fk = est.id
                AND est4.activityType_FK = at4.code
            WHERE est4.establishment_fk = est.id
              AND at4.status_FK IS NOT NULL
          )
          AND at3.status_FK IS NOT NULL
    ) AS 'status',
    est.authorizationNumber,
    reg.NAME AS 'region',
    mun.NAME AS 'municipality',
    ISNULL(usr.NAME,  '') + ISNULL(+ ' ' + usr.lastName,  '')
        AS 'created',
    ISNULL(usr2.NAME, '') + ISNULL(+ ' ' + usr2.lastName, '')
        AS 'updated',
    est.rowCreatedDT,
    est.rowUpdatedDT,
    CASE WHEN est.rowUpdatedDT >= est.rowCreatedDT
         THEN est.rowUpdatedDT
         ELSE est.rowCreatedDT
    END AS 'LatestCreatedOrModified'
FROM SACPAN_Establishments est
INNER JOIN SACPAN_EstablishmentActivities eact
    ON est.id = eact.establishment_FK
INNER JOIN SACPAN_ActivityTypes actTypes
    ON eact.activityType_FK = actTypes.code
INNER JOIN SACPAN_Regions reg
    ON est.region_FK = reg.code --
INNER JOIN SACPAN_Municipalities mun
    ON est.municipality_FK = mun.code
INNER JOIN SACPAN_ContactEstablishments ce
    ON ce.establishment_FK = est.id
INNER JOIN SACPAN_Contacts con
    ON ce.contact_FK = con.id
--JOIN SACPAN_Status stat ON stat.id = actTypes.status_FK
INNER JOIN SACPAN_Users usr
    ON usr.id = est.rowCreatedBy_FK
LEFT JOIN SACPAN_Users usr2
    ON usr2.id = est.rowUpdatedBy_FK
WHERE (con.ssn = @ssn OR @ssn = '*')
  AND eact.rowCreatedDT = (
    SELECT MAX(eact2.rowCreatedDT)
    FROM SACPAN_EstablishmentActivities eact2
    WHERE eact2.establishment_FK = est.id
)
--AND est.id = 6266
ORDER BY 'LatestCreatedOrModified' DESC

执行计划

4

2 回答 2

1

尝试将“活动”查询移动到左连接,看看它是否加快了速度。

于 2013-03-04T02:29:35.583 回答
0

我通过创建一个临时表并为其创建索引解决了这个问题,这消除了 select 语句中慢子查询的需要。然后我加入临时表,就像我加入普通表一样。

谢谢大家。

于 2013-03-10T23:15:47.423 回答