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

时间:2015-05-19 08:27:34

标签: mysql union

这是我第一次尝试使用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>";

1 个答案:

答案 0 :(得分:0)

您应该使用GROUP BY子句。

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

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