gpt4 book ai didi

php - 函数 SQL SUM 查询

转载 作者:行者123 更新时间:2023-11-29 01:16:24 24 4
gpt4 key购买 nike

我有一张表格,上面有这样的数字:

 ______________________________________
| axle_id | train_id | axle | distance |
|_________|__________|______|__________|
| 1 | 1 | 1 | 20 |
| 2 | 1 | 2 | 50 |
| 3 | 1 | 3 | 200 |
| 4 | 1 | 4 | 50 |
| 5 | 1 | 5 | 200 |
| 6 | 1 | 6 | 50 |
| 7 | 1 | 7 | 200 |
| 8 | 1 | 8 | 50 |
|_________|__________|______|__________|

现在我想对它们进行计数并使用 SUM 进行计算。我现在拥有的代码:

function count_axles($id) {
$sql = "SELECT sum(distance)/(25000)*(100) as totaldistance from axle WHERE train_id = :train_id";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(":train_id", $id, PDO::PARAM_STR);
$sth->execute();
return $sth->fetchAll();
}

我通过以下方式调用此函数:

<?php
$count_axle = $database->count_axles($_GET['train_id']);
?>
<?php
foreach($count_axle as $counting){
}

echo $counting['totaldistance'];
?>

现在输出是正确的。
(3.2800000000000002) 这是 25.000 的百分比
但我想添加 5000 个:

$sql = "SELECT sum(distance)+(5000)/(25000)*(100) as totaldistance from axle WHERE train_id = :train_id";

但是当我这样做时,输出会随机生成如下内容:840

为什么会这样,我该如何解决?

最佳答案

基础数学。你在做什么

                       5000
sum(distance) + --------------
25000 * 100

当你真正想要的时候

  sum(distance)  + 5000
------------------------
25000 * 100

尝试

SELECT (sum(distance)+(5000))/(25000)*(100)
^--------------------^

相反。注意额外的括号。

记住旧的 BEDMAS 助记符:括号、指数、除法、乘法、加法、减法...

关于php - 函数 SQL SUM 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29774855/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com