MySQL更新和查询或PHP中的Sum

I have no idea How can it be done or is it possible In Query.? Can be done in PHP.? If So any Idea or examples.

Here I have 2 tables.

Review

id    pid   published
--    ---   ---------
 1     12           0
 2     14           1
 3     16           1

Rating

id   rid   ratings                 sum
--   ---   ---------------------   -------
 1     2   4,5,3,3,3.5,5,5,5,4,5   42.5000
 2     4   4,5,3,3,3.5,5,5,5,4,5   42.5000
 3     1   5,5,4,4,5,5,4,4,4,4     44.0000

What I would Like to Do is

  1. Update the Rating table based on Review.id = Rating.rid.
  2. Update ratings field where ever Is find 3 or 2 or 1 update to 4 like example this 4, 5, 3, 3, 3.5, 5, 5, 5, 4, 5 should be 4, 5, 4, 4 ,4, 5, 5, 5, 4, 5
  3. Based On update ratings field SUM field should Automatic Update the Sum of the rating values. Example this 42.5000 should be 45.0000

I tried to explain my question if it is not clear please ask me to Modify or give you more detail.

My tables are exact same as example. ratings field has text data type. There Is no Another tables for ratings.

Any helps will be highly appreciate.

Thanks You.

  • Select Rating row (SELECT * FROM Rating WHERE rid=YOUR_RID)

  • Fetch data in PHP (mysqli_fetch(), PDOStatement->fetch(), etc.)

  • For transition string ratings to array use explode function

  • For interaction with array you may use foreach cycle.

    $sum = 0;

    foreach ($array as &$rating) {

    if($rating < 4) $rating=4;

    $sum+=$rating;

    }

You should redesign your DB structure and store ratings' values in another table, for example, with structure like this

id | review_id | value

and then you would do all these things easily.

If this change is impossible, you probably should do it in PHP. I mean, you query all necessary data, explode ratings by , in array and do your operations over array.

But I highly recommend to move ratings in another table.