这是我第一次尝试使用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>";
答案 0 :(得分:0)
您应该使用GROUP BY
子句。
SELECT gender,
COUNT(1) AS no_of_members
FROM members
GROUP BY gender;
这会产生与您表中不同性别一样多的行。