There are two tables "items" and "ratings". Items can have many ratings.
Currently I am trying to retrieve a sorted collection of "items" based on the rating. So, I require to sort the collection according to average of values in rating.
Thus, I implemented this query.
SELECT items.id, items.description, avg(ratings.value) as average
FROM `items`
INNER JOIN `ratings` ON `ratings`.`item_id` = `items`.`id`
WHERE `items`.`type` IN ('Book')
GROUP BY ratings.item_id
ORDER BY average desc;
Output(I have not pasted the whole description, since it is too long to fit):
+-----+----------------------------+---------+
| id | description | average |
+-----+----------------------------+---------+
| 241 | Into the intrigue and vio | 3.0000 |
| 242 | Teams can be a driving fo | 2.0000 |
| 243 | NULL | 5.0000 |
| 244 | In Temptations of the Wes | 1.0000 |
| 245 | NULL | 4.0000 |
+-----+----------------------------+---------+
Here, the items did not come out sorted accordingly.
Now, when I removed the description from selection, the results were coming out correct.
So, assuming that the problem was occurring due to length of the text field, I limited the description field length to a lower value. Here, the query is working properly as well. (After trying out multiple values, it figured the breakpoint it at 512)
SELECT items.id, left(items.description, 512), avg(ratings.value) as average
FROM `items`
INNER JOIN `ratings` ON `ratings`.`item_id` = `items`.`id`
WHERE `items`.`type` IN ('Book')
GROUP BY ratings.item_id
ORDER BY average desc;
Output (For smaller trimming value):
+-----+----------------------------+---------+
| id | left(items.description,25) | average |
+-----+----------------------------+---------+
| 243 | Into the intrigue and vio | 5.0000 |
| 245 | Teams can be a driving fo | 4.0000 |
| 241 | NULL | 3.0000 |
| 242 | In Temptations of the Wes | 2.0000 |
| 244 | NULL | 1.0000 |
+-----+----------------------------+---------+
So, is this a bug or an expected behavior or am I missing out on something ?