您可以使用带有CASE
表达式的聚合函数在单个查询中执行此操作:
select
sum(case when number=0 then 1 else 0 end) TotalNumber,
sum(case when answer='N' then 1 else 0 end) TotalAnswer
from yourtable
请参阅带有演示的 SQL Fiddle
要通过 PHP 获取这些结果,您可以使用mysqli_
或PDO
API:
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT Sum(CASE
WHEN number = 0 THEN 1
ELSE 0
end) TotalNumber,
Sum(CASE
WHEN answer = 'N' THEN 1
ELSE 0
end) TotalAnswer
FROM yourtable";
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
$row = mysqli_fetch_assoc($result);
echo "There are " . $row['TotalNumber'] . "entries in the number field with a value of 0";
echo "There are " . $row['TotalAnswer'] . "entries in the answer field with a value of N";
/* free result set */
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
?>