PHP / MYSQL子查询导致未定义的索引错误

时间:2019-07-12 19:10:19

标签: php mysql subquery

我正在尝试使用PDO进行子查询:

$stmt = $pdo->prepare("SELECT sum(ros_ranking) FROM (SELECT ros_ranking FROM players WHERE teamid = 1 and positionid = 1 ORDER BY ros_ranking ASC LIMIT 1) AS totalrankings");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$num_rows= $stmt->rowCount();
echo "tqr= ".$row['totalrankings'];

我不断收到Notice: Undefined index: totalrankings in ...

ros_ranking绝对是我的Players表中具有数字的字段,并且确实存在teamid为1和positionid为1的情况。

有人在这里看到我在做什么错吗?仅供参考,如果我只将子查询作为主要查询,它就可以工作。因此,SELECT sum(ros_ranking) FROMAS totalrankings肯定有问题,但它们看起来非常简单。

3 个答案:

答案 0 :(得分:1)

别名使用/位置错误

您需要一个列名别名来进行总排名(而不是像表名一样)

$stmt = $pdo->prepare("SELECT sum(t.ros_ranking) totalrankings
        FROM (SELECT ros_ranking 
                FROM players 
                WHERE teamid = 1 
                AND positionid = 1 
                ORDER BY ros_ranking ASC LIMIT 1)  t");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$num_rows= $stmt->rowCount();
echo "tqr= ".$row['totalrankings'];

答案 1 :(得分:1)

total_rankings是子查询的别名,不是列的别名。您需要将AS totalrankings放在SUM()后面。

$stmt = $pdo->prepare("
    SELECT sum(ros_ranking) AS totalrankings 
    FROM (
        SELECT ros_ranking 
        FROM players 
        WHERE teamid = 1 and positionid = 1 
        ORDER BY ros_ranking ASC
        LIMIT 1) AS subquery");

但是子查询中的LIMIT 1意味着您将不会得到任何东西。子查询只返回1行,而一件事的总和就是那个值。

答案 2 :(得分:0)

尽管可以解决此问题,但通过为选定的列提供正确的别名,如果查询仅返回一列,则无需获取数组。请改用fetchColumn()

$stmt = $pdo->prepare("SELECT ...");
$stmt->execute();
$totalrankings = $stmt->fetchColumn();
$num_rows= $stmt->rowCount();
echo "tqr= ".$totalrankings;