如何计算第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();
}