How can the query code of my ranking and upper and lower ranking be optimized?

SELECT
    T.[ID] AS ID, 
    A.UserName AS ,
    T. AS , 
    T. AS ,  
    W.[ID] AS ID, 
    B.UserName AS ,    
    W. AS ,
    W. AS ,
    X.[ID] AS ID,
    C.UserName AS ,
    X. AS ,
    X. AS 
FROM
    (
    SELECT
    MX.[ID],
        SUM (CONVERT ( DECIMAL ( 13, 1 ), MX.[] )) AS [],
        row_number () OVER ( ORDER BY SUM ( CONVERT ( DECIMAL ( 13, 1 ), MX.[] ))  DESC ) 
    FROM
        dbo.[MX_] AS MX
    GROUP BY MX.[ID]
    ) T 
    LEFT JOIN (
            SELECT
                MX.[ID],
                SUM (CONVERT ( DECIMAL ( 13, 1 ), MX.[] )) AS [],
                row_number () OVER ( ORDER BY SUM ( CONVERT ( DECIMAL ( 13, 1 ), MX.[] ))  DESC ) 
            FROM
                dbo.[MX_] AS MX
            GROUP BY MX.[ID]
    ) W  ON T. = W.-1
    LEFT JOIN (
            SELECT
                MX.[ID],
                SUM (CONVERT ( DECIMAL ( 13, 1 ), MX.[] )) AS [],
                row_number () OVER ( ORDER BY SUM ( CONVERT ( DECIMAL ( 13, 1 ), MX.[] ))  DESC ) 
            FROM
                dbo.[MX_] AS MX
            GROUP BY MX.[ID]
    ) X  ON T. = X.+1
    LEFT JOIN dbo.Sys_Users as A ON T.[ID] = A.UserID 
    LEFT JOIN dbo.Sys_Users as B ON W.[ID] = B.UserID
    LEFT JOIN dbo.Sys_Users as C ON X.[ID] = C.UserID
    WHERE   T.[ID] = -8191
Jul.12,2022

it is not recommended to write too complicated.

you can first find out your ranking and score
, and then find out the lowest ranking above your ranking (before) and the highest ranking below your ranking (after)

.

ranking is a continuous direct +-1 bit more convenient.


something like that. This sql is analyzed by explain.
can also take out subqueries to make related queries. Slowly, sql like this is cached directly


.

do not attempt to complete complex calculations through a sql, there is a risk that the program will time out or drag down the server.

SELECT
    A.UserName AS ,
    B.UserName AS ,  
    C.UserName AS ,
...
    LEFT JOIN dbo.Sys_Users as A ON T.[ID] = A.UserID 
    LEFT JOIN dbo.Sys_Users as B ON W.[ID] = B.UserID
    LEFT JOIN dbo.Sys_Users as C ON X.[ID] = C.UserID

the leftjoin here can be mentioned, and then the corresponding fields can be obtained through the program single table query.
can reduce response time by N times.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1ea66b9-1dd3.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1ea66b9-1dd3.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?