![](/img/trans.png)
[英]How can I add a store a cookie function to this five star rating system?
[英]how can i query the number of users who voted, for star rating system
我有一张表格,希望获得5票,4票,3票,2票和1票的投票人数
id user_id question_id rating
1 1 1 3
2 2 1 3
3 3 1 4
我希望结果如下:forquestion_id 1
* * * * * (0)
* * * * (1)
* * * (2)
* * (0)
* (0)
这是我的代码:
$con=mysqli_connect("localhost","root","","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"SELECT * FROM `survey_answers`");
for($i=5;$i>0;$i--){
for($j=0;$j<$i;$j++){
echo " * ";
}
echo "<br>";
}
这应该为您工作,只需将表名和问题ID替换为您想要的任何内容。
SELECT COUNT(*) AS vote_count, rating FROM ratings_table WHERE question_id = ? GROUP BY rating
如果您想一次获得所有问题,可以使用:
SELECT COUNT(*) AS vote_count, rating FROM ratings_table GROUP BY rating, question_id
这应该可以解决问题:
SELECT question_id
, rating
, COUNT(user_id) voteCount
FROM survey_answers
GROUP BY question_id, rating
我假设您正在得到所有问题及其票数。 按照设计,用户只能对每个问题投票一次。
这也许是解决问题的一种愚蠢的方法。 但是可以使用纯sql完成。 请尝试这个:
select concat(tmp.star,' (',ifnull(cnt,0),')')as ratings from(
select 1 as rating,'*' as star union all
select 2, '**' union all
select 3, '***' union all
select 4, '****' union all
select 5, '*****'
) tmp
left join (
select rating,count(1) cnt
from survey_answers
where question_id = 1
group by question_id,rating
) as tbl on tbl.rating = tmp.rating
order by tmp.rating desc
结果应如下所示:
ratings
---------
***** (0)
**** (1)
*** (2)
** (0)
* (0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.