在SELECT中返回上面的2行和前面的2行

时间:2014-07-16 00:51:46

标签: mysql select subquery

朋友,

我想创建一个查询,让我返回上面的2行和所选ID下面的2行,但必须通过排名进行比较。

创建联赛表的查询。

SET @rowId :=0;
SELECT 
    @rowid:= @rowid + 1 AS ranking, 
    tabelaCompleta.*
FROM
(SELECT 
    tbl_timeCartola.nomeTime AS nomeTime, 
    SUM( tbl_ponto.ponto ) AS totalPontos, 
    tbl_timeCartola.FK_loginID
FROM tbl_ponto
INNER JOIN tbl_timeCartola ON tbl_timeCartola.FK_loginID = tbl_ponto.FK_loginID
WHERE tbl_timeCartola.FK_loginID IN ( SELECT FK_loginID FROM tbl_campeonatoUsuario WHERE FK_campeonatoID = '1' )
GROUP BY tbl_timeCartola.nomeTime
ORDER BY totalPontos DESC ) tabelaCompleta;

此查询返回:

+---------+-------------------+-------------+------------+
| ranking | nomeTime          | totalPontos | FK_loginID |
+---------+-------------------+-------------+------------+
|       1 | Mathemio Greus-SB |      612.90 |          7 |
|       2 | CR Hipotenusa VG  |      572.67 |          4 |
|       3 | Zica Danada       |      549.20 |          6 |
|       4 | FC LEEDS UNITED   |      516.12 |          8 |
|       5 | Bradock  F.C      |      503.51 |          5 |
+---------+-------------------+-------------+------------+

1 个答案:

答案 0 :(得分:0)

试试这段代码。排名来自两个不同的内联视图。然后,使用排名来连接它们(如果第二个内联视图的排名是-1,=,或者比第一个内联视图的排名+1)。数据将针对selectedId进行过滤。

SET @rowId1 :=0;
SET @rowId2 :=0;
SET @selectedId := 8;

SELECT
    tabela_ordenada2.*
FROM
(
SELECT 
    @rowId1 := @rowId1 + 1 AS ranking, 
    tabelaCompleta.*
FROM
(SELECT 
    tbl_timeCartola.nomeTime AS nomeTime, 
    SUM( tbl_ponto.ponto ) AS totalPontos, 
    tbl_timeCartola.FK_loginID AS FK_loginID
FROM tbl_ponto
INNER JOIN tbl_timeCartola ON tbl_timeCartola.FK_loginID = tbl_ponto.FK_loginID
WHERE tbl_timeCartola.FK_loginID IN ( SELECT FK_loginID FROM tbl_campeonatoUsuario WHERE FK_campeonatoID = '1' )
GROUP BY tbl_timeCartola.nomeTime
ORDER BY totalPontos DESC ) tabelaCompleta
) tabela_ordenada1
INNER JOIN
(
SELECT 
    @rowId2 := @rowId2 + 1 AS ranking, 
    tabelaCompleta.*
FROM
(SELECT 
    tbl_timeCartola.nomeTime AS nomeTime, 
    SUM( tbl_ponto.ponto ) AS totalPontos, 
    tbl_timeCartola.FK_loginID AS FK_loginID
FROM tbl_ponto
INNER JOIN tbl_timeCartola ON tbl_timeCartola.FK_loginID = tbl_ponto.FK_loginID
WHERE tbl_timeCartola.FK_loginID IN ( SELECT FK_loginID FROM tbl_campeonatoUsuario WHERE FK_campeonatoID = '1' )
GROUP BY tbl_timeCartola.nomeTime
ORDER BY totalPontos DESC ) tabelaCompleta
) tabela_ordenada2
ON (tabela_ordenada2.ranking = tabela_ordenada1.ranking - 1 OR tabela_ordenada2.ranking = tabela_ordenada1.ranking OR tabela_ordenada2.ranking = tabela_ordenada1.ranking + 1)
WHERE tabela_ordenada1.FK_loginID = @selectedId;