我有一张桌子,我想要投票给5个评分,4个评分,3个评分,2评级和1个评分的用户数
id user_id question_id rating
1 1 1 3
2 2 1 3
3 3 1 4
我希望结果如下:for question_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>";
}
答案 0 :(得分:1)
这应该对您有用,只需将表名和问题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
答案 1 :(得分:0)
这应该可以解决问题:
SELECT question_id
, rating
, COUNT(user_id) voteCount
FROM survey_answers
GROUP BY question_id, rating
我假设您收到所有问题及其各自的投票数。按设计,用户每个问题只能投票一次。
答案 2 :(得分:0)
这可能是解决问题的愚蠢方法。但它可以用纯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)