I have a table called `ranks` which stores a 1-7 value and connects it with an `item` and `user` id.

Like this: `id | userid | value | itemid`.

To display an item's rating, I calculate the sum of all the values (1-7) where `itemid=?` and divide it by the total number of rows. But I have no value stored in the `items` table itself.

Fetch average rating:

```
    // total

    $stmt = $conn->prepare("SELECT SUM(value) as total FROM ranks WHERE itemid=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->bind_result($total);
    $stmt->fetch();
    $stmt->close();

    // num of rows

    $stmt = $conn->prepare("SELECT COUNT(value) FROM ranks WHERE itemid=?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->bind_result($count);
    $stmt->fetch();
    $stmt->close();

    $avg = $total/$count;

```

But I have no idea how to **sort by highest rated** unless I have the rating stored in the `items` table itself. Is it possible with the separate `ranks` table?