我有一个SQL数据库,其中包含以下结构和信息:
idClub Pts GD
1 3 2
2 4 0
3 5 -1
4 0 -3
5 9 5
6 1 2
7 3 1
8 0 -2
9 6 0
10 7 5
如果是的话:
$ result = $ mysqli-> query(“SELECT * FROM table ORDER BY Pts Desc,GD 商品说明“);
它将实现这一目标:
idClub Pts GD
5 9 5 //Row Number = 1
10 7 5 //Row Number = 2
9 6 0 //Row Number = 3
3 5 -1 //Row Number = 4
2 4 0 //Row Number = 5
1 3 2 //Row Number = 6
7 3 1 //Row Number = 7
6 1 2 //Row Number = 8
8 0 -2 //Row Number = 9
4 0 -3 //Row Number = 10
每个idClub都有自己的个人资料页面 - profile.php?Id = X - 我需要在其中显示带有id的俱乐部,以及表格中上下两个队伍。
有没有办法知道$ result中给定值的行号(位置)? 例如,profile.php?Id = 3它将是4;对于profile.php?Id = 1它将是6,依此类推..
例如,对于profile.php?Id = 3,我需要一个$ result来提供以下内容:
idClub Pts GD
10 7 5
9 6 0
3 5 -1
2 4 0
1 3 2
提前致谢。
答案 0 :(得分:1)
首先,采取您目前的查询,
SELECT
*
FROM
atable
ORDER BY
Pts DESC,
GD DESC
并使用涉及变量赋值的众所周知的技术向其添加行编号:
SELECT
atable.*,
@row := @row + 1 AS row
FROM
atable
CROSS JOIN
(SELECT @row := 0) AS p
ORDER BY
Pts DESC,
GD DESC
这将根据指定的顺序为您的行分配排名。现在,如果我们知道与指定的idClub
关联的行号,我们只需将上述查询用作派生表,并在
WHERE
row BETWEEN @idXrow - 2 AND @idXrow + 2
我们可以找出@idXrow
值。为此,我们可以向子查询添加一个变量赋值:
@idXrow := CASE idClub WHEN 3 THEN @row ELSE @idXrow END
其中3
是指定的idClub
值 - 在最终查询中,可能需要使用参数引用替换它。无论如何,完成工作的complete query看起来像这样:
SELECT
row,
idClub,
Pts,
GD
FROM
(
SELECT
atable.*,
@row := @row + 1 AS row,
@idXrow := CASE idClub WHEN 3 THEN @row ELSE @idXrow END
FROM
atable
CROSS JOIN
(SELECT @row := 0) AS p
ORDER BY
Pts DESC,
GD DESC
) AS s
WHERE
row BETWEEN @idXrow - 2 AND @idXrow + 2
;
答案 1 :(得分:0)
如果您只是在$result
中讨论查询,则可以跟踪在您的打印循环中迭代的变量,如下所示:
$result = $mysqli->query("SELECT * FROM table ORDER BY Pts Desc, GD Desc");
$c = 0;
echo "<table>\n<tr>\n<td>idClub</td>\n<td>Pts</td>\n<td>GD</td>\n<td>Row #</td>\n</tr>\n";
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>\n<td>$row[idClub]</td>\n<td>$row[Pts]</td>\n<td>$row[GD]</td>\n<td>$c</td>\n</tr>\n";
$c++;
}
echo "</table>";
答案 2 :(得分:0)
另一种可能的解决方案:
$selClub = $_GET["Id"];
$result = $mysqli->query("SELECT idClub FROM table");
for ($i = 1; $i <= $result->num_rows; $i++) {
if ( $result->fetch_object()->idClub == $selClub )
$position = $i;
}
if ( $position <= 2 ) {
$result = $mysqli->query("SELECT * FROM table ORDER BY Pts Desc, GD Desc LIMIT 0, 5");
} elseif ( $position >= $result->num_rows - 1 ) {
$result = $mysqli->query("SELECT * FROM table ORDER BY Pts Desc, GD Desc LIMIT ($result->num_rows-5), 5");
} else {
$result = $mysqli->query("SELECT * FROM table ORDER BY Pts Desc, GD Desc LIMIT ($position-3), 5");
}
对第一个和第二个$结果使用相同的名称实际上是一个问题吗?