SQL / PHP:计算平均男性/女性

时间:2011-07-21 14:47:01

标签: php sql

$sql = $connect->prepare("SELECT e.ID, u.sex FROM discos_events e
INNER JOIN discos_events_guests eg ON (e.ID = eg.eID)
INNER JOIN users u ON (eg.uID = u.id)
WHERE e.dID =:id");
$sql->bindValue(":id", $cID);
$sql->execute();
$total = $sql->rowCount();
$male = 0;
$female = 0;
while($sex = $sql->fetch()){
    if($sex["sex"] == "male"){
        $male++;
    }else{
        $female++;
    }
}
$averageMales = $male/$total;
$averageFemales = $female/$total;

这可以做得更简单吗?

如果没有,这不能正常工作,如果有两个男性和0个女性,$ averageMales返回1而$ averageFemales返回0。

我希望它能够在过程中返回,例如100%现在没有任何女性,女性为0%。

2 个答案:

答案 0 :(得分:3)

无需使用单独的查询:

SELECT count(males.id) / (count(males.id) + count(females.id)) * 100 AS male_percentage
FROM discos_events
JOIN discos_events_guests ON discos_events_guests.eID = discos_events.ID
LEFT JOIN users males ON males.sex = 'male' AND males.id = discos_events_guests.uID
LEFT JOIN users females ON females.sex = 'female' AND females.id = discos_events_guests.uID
WHERE discos_events.dID = :id

答案 1 :(得分:2)

提出两个问题:一个得到女性,得到总数。然后除。顺便说一下,SQL中有COUNT(*)函数比执行完整查询然后用$sql->rowCount();

获取它更快

计算总客人数:

"SELECT COUNT(*)
FROM discos_events e
INNER JOIN discos_events_guests eg ON (e.ID = eg.eID)
INNER JOIN users u ON (eg.uID = u.id)
WHERE e.dID =:id"

计算女性人数:

"SELECT COUNT(*)
FROM discos_events e
INNER JOIN discos_events_guests eg ON (e.ID = eg.eID)
INNER JOIN users u ON (eg.uID = u.id)
WHERE e.dID =:id
AND eg.sec='female'"