如何计算第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值
1个产品1 1500000
2个产品1 1400000
3个产品1 1300000
4个产品2 1000000
5个产品2 900000
6个产品2 800000
答案 0 :(得分:2)
您只需一个查询即可做到这一点:
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();
}
答案 1 :(得分:0)
我不确定,但是我认为这就是您想要的。
$sql = "SELECT p1.value 'tbproduct_value', p2.value 'tbvalproduct_value'
FROM tbproduct p1 join tbvalproduct p2 on p1.nameproduct = p2.nameproduct
WHERE nameproduct = '".$product."'";
$q = mysqli_query( $con, $sql );
while( $res = mysqli_fetch_assoc( $q ) ){
echo $res['product']."=".$res['tbproduct_value']. $res['tbvalproduct_value'] . "<br>";
}
请及时通知我们!
欢呼