【问题标题】:Count number of rows in SELECT with WHERE clause使用 WHERE 子句计算 SELECT 中的行数
【发布时间】:2017-04-07 09:58:26
【问题描述】:

我有一个表格,其中包含以下格式的“社区”和“状态”两列:

community     status
Zoo            1
Zoo            1
Zoo            0
Zoo            1

现在我想计算 Zoo 中有多少 status=1 的行; 对于上面的示例,我希望输出类似于“行数为 3”

现在,我可以查询 Zoo 列的状态为 1 的行,并回显结果以获取类似 111 的输出。

代码 sn-p 如下:

if (mysqli_connect_errno())
{
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT * FROM location WHERE (community = 'Zoo') AND (status = '1');";
$result = $mysqli->query($query);

while($row = $result->fetch_array())
{
    $rows[] = $row;
}

foreach($rows as $row)
{
    echo $row['status'];
}

$result->close();

【问题讨论】:

  • 你试过在sql中使用恰当命名的COUNT函数吗? techonthenet.com/sql/count.php
  • 试试SELECT count(*) FROM location WHERE (community = 'Zoo') AND (status = '1');
  • @Utsav 嗨,谢谢,伙计,它成功了。

标签: php mysql mysqli


【解决方案1】:

只需使用 mysqli_num_rows(); 函数

$q="select * from location where community='Zoo' AND status='1'";
$res=mysqli_query($con,$q);
echo mysqli_num_rows($res);

【讨论】:

    【解决方案2】:

    对于那些希望在未来计算特定查询的行数的用户: 注意:在带有 count(*) 和 echo $row['total'];**

    的查询中使用 AS total
    if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
    }
    
    $query = "SELECT count(*) AS total FROM location WHERE (community = 'Zoo') AND (status = '1');";
    $result = $mysqli->query($query);
    
    while($row = $result->fetch_array())
    {
    $rows[] = $row;
    }
    foreach($rows as $row)
    {
    echo $row['total'];
    }
    $result->close();
    

    输出:Zoo 的列状态为 1 的行总数为 3。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-06
      • 2012-02-12
      • 1970-01-01
      • 2014-10-12
      • 2015-02-14
      • 2011-09-19
      相关资源
      最近更新 更多