ai didi

php - 如果表mysqli中的同一列,如何计算行x和行y

转载 作者:搜寻专家 更新时间:2023-10-31 20:57:28 24 4
gpt4 key购买 nike

如何计算第 1 行和第 4 行同一列。

我的代码:

$qR1 = mysqli_query($con, "SELECT * FROM tbproduct WHERE nameproduct = '".$product."'");
while( $res1 = mysqli_fetch_assoc($qR1)){
$qR2 = mysqli_query($con, "SELECT * FROM tbvalproduct WHERE nameproduct = '".$res1['product']."' ");
while($res2 = mysqli_fetch_assoc($qR2)){
echo $res2['product']."=".$res2['value']."<br>";
}

}

输出:

1.product1 = 1500000
2.product1 = 1400000
3.product1 = 1300000
4.product2 = 1000000
5.product2 = 900000
6.product2 = 800000

我想要的:

-row 1 + row 4 // 1500000 + 1000000
-row 2 + row 5 // 1400000 + 900000
-row 3 + row 6 // 1300000 + 800000

示例表:

Id      product       value
---------------------------
1 product1 1500000
2 product1 1400000
3 product1 1300000
4 product2 1000000
5 product2 900000
6 product2 800000

最佳答案

您只需一个查询就可以做到这一点:

SELECT t1.product, t1.value
FROM tbvalproduct t1
INNER JOIN tbproduct t2
ON t1.nameproduct = t2.product
WHERE
t2.nameproduct = ?;

您更新的 PHP 代码:

$sql = "SELECT t1.product, t1.value FROM tbvalproduct t1 INNER JOIN tbproduct t2 ";
$sql .= "ON t1.nameproduct = t2.product WHERE t2.nameproduct = ?";

if ($stmt = $mysqli->prepare($sql)) {
$stmt->bind_param("s", $product);
$stmt->execute();
$result = $stmt->get_result();

while ($row = $result->fetch_assoc()) {

echo $row['product']."=".$row['value']."<br>";
}

$stmt->free_result();
$stmt->close();
}

关于php - 如果表mysqli中的同一列,如何计算行x和行y,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54515521/

24 4 0
文章推荐: php - 如何从 php 与 MySQLi 保持连接
文章推荐: php - sortKeys() 不对集合的键进行排序
文章推荐: php - 如何从 PHP 中的索引数组创建多维数组?
文章推荐: php - 如何从使用 foreach 循环创建的表单中检索 _POST 数据?
搜寻专家
个人简介

我是一名优秀的程序员,十分优秀!

滴滴打车优惠券免费领取
滴滴打车优惠券
全站热门文章
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com