开发者

MySQL order rank as a column

开发者 https://www.devze.com 2023-04-02 12:16 出处:网络
I have a MySQL query that selects data from multiple tables and then orders the results based on some arbitrary criteria as below:

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 *开发者_StackOverflow中文版, 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.


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;


put it in the select

((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 ranking
0

精彩评论

暂无评论...
验证码 换一张
取 消