选择行上方和下方的数据

时间:2016-06-30 16:18:53

标签: php mysql

我希望在网页上显示一个足球联赛表格的片段。 我希望选择一个特定的团队(团队b),然后选择一个上方和下一个团队。

例如

              p  w  d  l
    team c    1  1  0  0
    team b    1  0  1  0
    team a    1  0  0  1

接下来的一周可能是:

              p  w  d  l
    team d    2  2  0  0
    team b    2  1  1  0
    team c    2  1  0  1

等等。

如何才能最好地解决这个问题?它是在MySQL中使用查询还是我希望在PHP中使用它?

谢谢

1 个答案:

答案 0 :(得分:0)

select * from games order by w;
+--------+------+------+------+------+
| name   | p    | w    | d    | l    |
+--------+------+------+------+------+
| team b |    1 |    0 |    1 |    0 |
| team a |    1 |    0 |    0 |    1 |
| team c |    1 |    1 |    0 |    0 |
| team d |    2 |    2 |    0 |    0 |
+--------+------+------+------+------+
4 rows in set (0.00 sec)


mysql> SELECT NAME,P,W,D,L,@curRank := @curRank + 1 as rank FROM 

(从w DESC的游戏顺序中选择NAME,P,W,D,L)x,(SELECT @curRank:= 0)r;

+--------+------+------+------+------+------+
| NAME   | P    | W    | D    | L    | rank |
+--------+------+------+------+------+------+
| team d |    2 |    2 |    0 |    0 |    1 |
| team c |    1 |    1 |    0 |    0 |    2 |
| team b |    1 |    0 |    1 |    0 |    3 |
| team a |    1 |    0 |    0 |    1 |    4 |
+--------+------+------+------+------+------+
4 rows in set (0.01 sec)


    mysql> SELECT NAME,P,W,D,L,rank FROM 
(SELECT NAME,P,W,D,L,@curRank := @curRank + 1 as rank,
if(name ="team b",@curRank := @curRank*-1,0)  AS required_rank 
FROM (select NAME,P,W,D,L from games order by w DESC) x,
(SELECT @curRank := 0) r ) p order by abs(rank) desc limit 3;
+--------+------+------+------+------+------+
| NAME   | P    | W    | D    | L    | rank |
+--------+------+------+------+------+------+
| team b |    1 |    0 |    1 |    0 |    3 |
| team c |    1 |    1 |    0 |    0 |    2 |
| team a |    1 |    0 |    0 |    1 |   -2 |
+--------+------+------+------+------+------+
3 rows in set (0.00 sec)