Hi there!
I've got a little problem with correct query and hope you can help me. My testing tables structures are as follow:
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
) ;
CREATE TABLE IF NOT EXISTS `user_throws` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`length` int(11) DEFAULT NULL,
PRIMARY KEY (`id`,`user_id`),
) ;
The relations between them is many to one (a user can have many throws). The thing is I need to make a somekind ranking page for all users let's say top 100 throwers. So I need a query result to be:
- Filtered by users so only the users who have any throws and the length of throw is greater than 0 is correct record.
- Filtered by duplicates so only unique users appear on the list (GROUP BY I suppose).
- Sorted by length of throws so only the best (greatest) result will be appended.
For that purpose I wrote the query:
SELECT `user_throws`.`length` , `users` . *
FROM `users`
JOIN `user_throws` ON ( `user_throws`.`user_id` = `users`.`id` )
WHERE `user_throws`.`length` > '0'
GROUP BY `users`.`id`
ORDER BY `user_throws`.`length` DESC
But the problem is results are not being sorted by longest throw. It filters the throws with length greater than 0 and displays unique users but the length appended does not correspond with desired sorting. I found out that the length
value is the value of throw with lowest user_throws
.id
that is associated with the user. How should the correct query look like?