SQL/PHP: Counting average male/females

梦想的初衷 提交于 2019-12-13 18:11:35

问题


$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;

Can this be done any simpler?

If not, this does not work properly, if there's two males and 0 females, $averageMales return 1 and $averageFemales return 0.

I want it to return in procentages, e.g 100% now when theres not any females, and females 0%.


回答1:


No need to use separate queries:

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



回答2:


Make two queries: one getting the females, on getting the total. Then divide. By the way, there is a COUNT(*) function in SQL wich is way faster than executing a full query and then fetching it with $sql->rowCount();

Counts the total number of guests:

"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"

Counts the number of females:

"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'"


来源:https://stackoverflow.com/questions/6777978/sql-php-counting-average-male-females

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!