Вот мой стол. Тип 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