我需要获取 while 循环内的数组的最大值并将该值绑定(bind)到一个变量,但是当我尝试时,我得到多个结果,而不仅仅是一个。
这是第一个表的示例,其中我获取了需要与第二个表进行比较的当前值;
tbl name: table1
----------------------------
| id | type | category |
|----|---------|-----------|
| 1 | apple | red |
|----|---------|-----------|
| 3 | orange | yellow |
|----|---------|-----------|
| 4 | orange | red |
----------------------------
这是第二个表的示例,我在其中比较第一个表的当前值以找出金额;
tbl name: table2
-------------------------------------
| id | type | category | amount |
|----|---------|-----------|--------|
| 1 | apple | red | 50.00 |
|----|---------|-----------|--------|
| 2 | apple | green | 75.00 |
|----|---------|-----------|--------|
| 3 | orange | yellow | 20.00 |
|----|---------|-----------|--------|
| 4 | orange | red | 20.00 |
-------------------------------------
这是我的代码;
$select_table1 = "select * from table1";
$connect_table1 = mysqli_query($con, $select_table1);
while ($row_table1 = mysqli_fetch_array($connect_table1)) {
$type = $row_table1['type'];
$category = $row_table1['category'];
$select_table2 = "select * from table2 where type in('$type') and category in('$category')";
$connect_table2 = mysqli_query($con, $select_table2);
while ($row_table2 = mysqli_fetch_array($connect_table2)) {
$amount = array(
$row_table2['amount']
);
$max = max($amount);
echo "$max<br/>";
}
}
这给了我;
50.00
20.00
20.00
我只需要最高金额,即 50.00
我做错了什么?
最佳答案
将 JOIN
与聚合函数 MAX()
结合使用来获取结果。这将执行一个查询,并且不需要额外的 PHP 逻辑。
$query = 'SELECT MAX(t2.amount) as maxAmount
FROM table2 t2
JOIN table1 t1
ON t1.type = t2.type
AND t1.category = t2.category';
$query = $con->query($query);
$result = $query->fetch_assoc();
echo $result['maxAmount'];
。参见 SQLFiddle
关于php while循环中数组的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55524265/