I’m doing a query on a set of users that returns the users within a specific radius. The users belong to 1 of 3 different types of user groups. I need to sort the return list by showing the users from group 1 (sorted by distance) and then the users from group 2 & 3 combined (sorted by distance). I could easily use an ORDER BY clause, but I don’t know how to be sure that groups 2 & 3 are combined together in the results.
Here is the statement that returns the users first by group 1, then 2, then 3 and sorted by distance inside those groups. I need to return group 1, then 2&3, sorted by distance.
Also I’m not sure if I’m using the INNER JOIN properly, should this be a LEFT JOIN?
SELECT
SQL_CALC_FOUND_ROWS
a.*,
b.group_id,
ROUND(( 3959 * acos( cos( radians( $lat ) ) * cos( radians( a.latitude ) ) * cos( radians( a.longitude ) - radians( $lon ) ) + sin( radians( $lat ) ) * sin( radians( a.latitude ) ) ) ), 1) AS distance
FROM `users` AS a
INNER JOIN `user_group_map` AS b
ON a.`id` = b.`user_id`
HAVING distance <= $radius
ORDER BY
b.`group_id` DESC,
distance ASC
You can use an
ORDER BY CASEto conditionally apply the order forcing group 1 first. I think this should do the job:The
CASEstatement returns 0 forgroup_id = 1and 1 for any other value ofgroup_id. The 0 sorts ahead of the 1, and these two subgroups (0 & 1) are then subordered bydistance ASCsogroup_id2 & 3 sort together.