一尘不染

SQL NOT IN可能存在性能问题

sql

我试图重构一些旧代码…我重构了下面的当前代码,并突出显示了NOT IN导致性能问题的语句。我试图NOT IN用左外部联接重写该部分。

任何人都可以提供帮助,或者在可能的情况下提出更好的建议吗?

SELECT 
    left(unique_id,16) AS casino_id , 
    right(unique_id,24) AS game_id   
FROM (  
        SELECT 
            distinct o.casino_id + g.game_id AS unique_id      
        FROM 
            game g INNER JOIN Bet b
            ON g.game_id = b.game_id
            INNER JOIN CasinoUser u 
            ON b.user_id = u.user_id
            INNER JOIN onewalletcasino o  
            ON u.casino_id = o.casino_id
        WHERE 
            game_start between dateadd(mi, -180, getdate()) 
            and dateadd(mi, -5, getdate())  
            and b.[status] <> 'P'
     ) t 
WHERE  
   unique_id NOT in  
    ( SELECT casino_id + game_id  AS casino_id 
      FROM 
        thirdpartysettlecalled  
      WHERE 
        [status] = 'Y')
ORDER BY casino_id

阅读 111

收藏
2021-05-23

共1个答案

一尘不染

您有一个列级联,可防止任何索引的使用

尝试不存在将分别支持2列

SELECT distinct
     o.casino_id, g.game_id
FROM 
    game g 
    INNER JOIN 
    Bet b ON g.game_id = b.game_id
    INNER JOIN
    CasinoUser u ON b.user_id = u.user_id
    INNER JOIN
    onewalletcasino o  ON u.casino_id = o.casino_id
WHERE 
    game_start between dateadd(mi, -180, getdate()) 
                       and dateadd(mi, -5, getdate())  
    and
    b.[status] <> 'P'
    AND
    NOT EXISTS (SELECT *
           FROM 
              thirdpartysettlecalled   tp
           WHERE 
              tp.[status] = 'Y'
              AND
              tp.casino_id = o.casino_id AND tp.game_id = g.game_id)
ORDER BY
    casino_id

之后,检查您的索引或课程…

这也是EXCEPT的一个很好的用法(ORDER BY像UNION一样结束了:感谢@Damien_The_Unbeliever)

SELECT distinct
     o.casino_id, g.game_id
FROM 
    game g 
    INNER JOIN 
    Bet b ON g.game_id = b.game_id
    INNER JOIN
    CasinoUser u ON b.user_id = u.user_id
    INNER JOIN
    onewalletcasino o  ON u.casino_id = o.casino_id
WHERE 
    game_start between dateadd(mi, -180, getdate()) 
                       and dateadd(mi, -5, getdate())  
    and
    b.[status] <> 'P'

EXCEPT
SELECT tp.casino_id, tp.game_id
FROM thirdpartysettlecalled   tp
WHERE tp.[status] = 'Y'

ORDER BY
    casino_id
2021-05-23