一起使用 MySQL 聚合函数和 UNION 运算符

Using MySQL aggregate functions and UNION operator together

这是我第一次尝试 MySQL 的 UNION 运算符,但是下面的代码给我一个 "undefined index: female".

的错误
$sql = "(SELECT COUNT(gender) AS male FROM members WHERE gender='m') 
        UNION 
        (SELECT COUNT(gender) AS female FROM members WHERE gender='f') 
        UNION 
        (SELECT COUNT(gender) AS no_gender FROM members WHERE gender='n') 
        ";
    $results = $con->query($sql);
    if ($row = $results->fetch_assoc()) {
        print $row["male"] . "<br>";
        print $row["female"] . "<br>";
        print $row["no_gender"] . "<br>";
    }

因此,基于 fancyPants 的解决方案,以下方法有效:

print "<table>";
$sql = "SELECT gender, COUNT(1) AS no_of_genders 
        FROM members 
        WHERE user_id = $user_id 
        GROUP BY gender";
$results = $con->query($sql);
while ($row = $results->fetch_assoc()) {
    print "<tr><td>" . $row["gender"] . "</td><td>" . $row["no_of_genders"] . "</td></tr>";
}
print "</table>";

您应该使用 GROUP BY 子句。

SELECT gender, 
COUNT(1) AS no_of_members
FROM members
GROUP BY gender;

这会产生与 table 中不同性别一样多的行。