Search code examples
mysqlranking

MySQL order rank as a column


I have a MySQL query that selects data from multiple tables and then orders the results based on some arbitrary criteria as below:

SELECT [columns] FROM (
  SELECT *, COUNT(*) as `matches`
    FROM [table1]
    JOIN [table2] USING (id)
    JOIN [table3] USING (id)
  WHERE [criteria]
  GROUP BY `id`
  ORDER BY `matches` DESC
) AS `grouped`
ORDER BY (
  (CASE WHEN [1st rank criteria] THEN 3 ELSE 0 END) +
  (CASE WHEN [2nd rank criteria] THEN 2 ELSE 0 END) +
  (CASE WHEN [3rd tank criteria] THEN 1 ELSE 0 END)
) DESC
LIMIT 100

This works fine, but my question is: can I have the ranking score displayed as a column? I've looked at trying to use variables, but I'm quite new to SQL so all this is a bit beyond me.

Sorry if this is an obvious question, but many thanks in advance for your time and assistance.


Solution

  • Try this:

    SELECT [columns],
       (
         (CASE WHEN [1st rank criteria] THEN 3 ELSE 0 END) +
         (CASE WHEN [2nd rank criteria] THEN 2 ELSE 0 END) +
         (CASE WHEN [3rd tank criteria] THEN 1 ELSE 0 END)
       ) AS MyRank
    
    FROM (
        SELECT *, COUNT(*) as `matches`
        FROM [table1]
        JOIN [table2] USING (id)
        JOIN [table3] USING (id)
        WHERE [criteria]
        GROUP BY `id`
        ORDER BY `matches` DESC
    ) AS `grouped`
    ORDER BY MyRank DESC
    LIMIT 100;