这是我的桌子。类型0适用于dislike
,类型1适用于like
。
id | userid | postid | type
1 | 465 | 20 | 0
2 | 465 | 21 | 1
3 | 466 | 20 | 1
4 | 466 | 21 | 0
5 | 467 | 20 | 1
6 | 467 | 21 | 0
现在,我的疑问是
$sql = $bdd->query('SELECT COUNT(id) AS cntLikes, postid, type FROM like_unlike WHERE type = 1 GROUP BY postid, type');
$sql = $bdd->query('SELECT COUNT(id) AS cntUnlikes, postid, type FROM like_unlike WHERE type = 0 GROUP BY postid, type');
这显示给我:
postid(20) -> 1 like
postid(21) -> 2 like1
postid(20) -> 2 dislikes
postid(21) -> 1 dislike
我想计算like
的百分比,并为每个postid
显示它。
$p = ($total_unlikes / ($total_unlikes+$total_likes)) * 100;
我试过
$sql = $bdd->query("SELECT postid, COUNT(CASE type WHEN '1' THEN 1 END) AS cntLikes, COUNT(CASE type WHEN '0' THEN 1 END) AS cntunlikes from like_unlike GROUP BY postid, type");
while ($donnees2 = $sql->fetch()) {
$total_likes = $donnees2['cntLikes'];
$total_unlikes = $donnees2['cntunlikes'];
$ratio = ($total_unlikes / ($total_unlikes+$total_likes)) * 100;
echo $donnees2['postid'],' nb likes',$total_likes,' nb dislikes',$total_unlikes,' percent',$p,'<br />';}
但它显示给我
postid(20) -> nb likes 1 -> nb dislikes 0 -> percent 100
postid(20) -> nb likes 0 -> nb dislikes 2 -> percent ->100
postid(21) -> nb likes 2 -> nb dislikes 0 -> percent -> 100
postid(21) -> nb likes 0 -> nb dislikes -> 1 percent ->100
以下是我想要的最终结果:
postid(20) -> nb likes 1 -> nb dislikes 2 -> percent 33
postid(21) -> nb likes 2 -> nb dislikes 1 -> percent ->66
答案 0 :(得分:0)
从type
移除GROUP BY
,这样您就不会为每种类型获得一个组(和一行),但两者都有一个组。