Search code examples
sqlmysqlgreatest-n-per-groupanalytic-functions

How to make this Mysql query work?


My query:

SELECT * 
FROM forum_topics 
WHERE cat_id IN(1,2,3,4,5,6,7) 
ORDER BY last_message DESC 
LIMIT 7

I want to get the biggest and only one value of each cat_id (7 values total). How to correct this query to make it work if it's even possible?

There is forum topics and each has value last_message and I want to get the latest topic's message's time. Hope it's clear.

Thank you


Solution

  • MySQL doesn't have analytical function support, which is what you're really after:

    SELECT x.*
      FROM (SELECT ft.*,
                   CASE 
                      WHEN @cat_id = ft.cat_id THEN @rownum := @rownum + 1
                      ELSE @rownum := 1
                   END AS rank,
                   @cat_id = ft.cat_id
              FROM FORUM_TOPICS ft
              JOIN (SELECT @rownum := 0, @cat_id := -1) r
          ORDER BY ft.cat_id, ft.last_message DESC)
     WHERE x.rank = 1
    

    This will provide a computed column called "rank", where the most recent row based on the last_message column will have the value of "1" per cat_id value. The outer query only gets the records whose rank value is one...