PHP的MYSQL查询知道有一个值,但它是空的

zi8p0yeb  于 2023-04-19  发布在  Mysql
关注(0)|答案(2)|浏览(136)

我有一个查询,它在表中查找给定名称的最大值并返回该数字。它在SQL控制台中工作得很好。但是,我试图获取该值,然后在HTML表中创建单选按钮,尽管有数据,但它是一个空集。它总是只有一个值,因此不需要数组。表中可以有多个同名条目,但不是同样的网。

$sqltankonly = "SELECT * FROM HoldingUnit WHERE tankfacility = 'test' AND net = '0' ORDER BY name"; // Select Holding Units that are not nets
$resulttankonly = $conn->query($sqltankonly); // Select Holding Units that are not nets unless they have something in them

if ($resulttankonly->num_rows > 0) {
  // Setup Table
  echo '<table><tr><th>Destination Tank</th><th>Net</th></tr>';
  while($row = $resulttankonly->fetch_assoc()) {
    echo '<tr><td><input type="radio" name="dtank" " value="' . $row["name"] . '" required>' . $row["name"] . '</td>';
    echo '<td>';

// Below is my problem *******************

    $sqlnetcapacity = 'SELECT MAX(net) FROM HoldingUnit WHERE name="' . $row["name"] . '"';
    $resultnetcapacity = $conn->query($sqlnetcapacity);
    $netcapacity = $conn->query('SELECT MAX(net) FROM HoldingUnit WHERE name="Test-01"')->fetch_object()->net;
    while($netcapacity > 0) {
      echo '<input type="radio" name="net" value="' . $netcapacity . '" />' . $netcapacity . ';
      $netcapacity = $netcapacity - 1;
    }
  }
  echo '</td></tr></table>';

我试着把$resultnetcapacity当作一个数组,用while循环代替fetch_object()。我试着只打印值,即使if语句证明有多于0个值,也没有显示。

o7jaxewo

o7jaxewo1#

结果中没有net列;您选择的列名为MAX(net)。您应该为MAX(net)的值指定别名。

$netcapacity = $conn->query('SELECT MAX(net) AS net FROM ...')->fetch_object()->net;

也不需要在循环中执行这些查询,可以将原始查询与MAX()查询连接起来。

SELECT t1.*, t2.net_capacity
FROM HoldingUnit AS t1
JOIN (
    SELECT name, MAX(net) AS net_capacity
    FROM HoldingUnit
    GROUP BY name
) AS t2 ON t1.name = t2.name

然后使用$netcapacity = $row['net_capacity']

uyto3xhc

uyto3xhc2#

感谢您的帮助,为我指明了正确的方向。下面的查询给了我所需要的结果...

SELECT m.name, m.net
FROM HoldingUnit m
    LEFT JOIN HoldingUnit b
        ON m.name = b.name
        AND m.net < b.net
WHERE b.net IS NULL;

这是我的结果

+---------+------+
| name    | net  |
+---------+------+
| Test-02 |    0 |
| Test-03 |    0 |
| Test-04 |    0 |
| Dead    |    0 |
| Test-01 |    1 |
+---------+------+

谢谢。当我在那些坦克上添加更多的坦克和更多的网时,这似乎对我的要求起作用。

相关问题