简体   繁体   English

如何查询星级评分系统的已投票用户数

[英]how can i query the number of users who voted, for star rating system

I have the table where i would like have the number of users who voted 5 ratings, 4 ratings, 3 ratings, 2 rating and 1 rating 我有一张表格,希望获得5票,4票,3票,2票和1票的投票人数

id  user_id question_id rating
1   1        1          3   
2   2        1          3       
3   3        1          4   

I would expect the result like the following: for the question_id 1 我希望结果如下:forquestion_id 1

* * * * * (0)
* * * * (1)
* * * (2)
* * (0)
* (0)

This is my code: 这是我的代码:

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

}

This should work for you, just replace the table name and the question id with whatever you want. 这应该为您工作,只需将表名和问题ID替换为您想要的任何内容。

SELECT COUNT(*) AS vote_count, rating FROM ratings_table WHERE question_id = ? GROUP BY rating

if you want to get all the questions at once you can use: 如果您想一次获得所有问题,可以使用:

SELECT COUNT(*) AS vote_count, rating FROM ratings_table GROUP BY rating, question_id

This should do the trick: 这应该可以解决问题:

SELECT question_id
    , rating
    , COUNT(user_id) voteCount
    FROM survey_answers
    GROUP BY question_id, rating

I am assuming that you are getting all the questions and its respective count of votes. 我假设您正在得到所有问题及其票数。 And by design, users can only vote once per question. 按照设计,用户只能对每个问题投票一次。

This maybe a silly way to solve your problem. 这也许是解决问题的一种愚蠢的方法。 But it can be done with pure sql. 但是可以使用纯sql完成。 Please try this : 请尝试这个:

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

The result should be looks like this : 结果应如下所示:

ratings
---------
***** (0)
**** (1)
*** (2)
** (0)
* (0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM