-1

Im have been query the database to collectively fetch latest record or each item using PARTITION and ROW_COUNT() which works on MariaDB version 10.4* but i want to query the same on a MySQL version 5.7* database but it doesn't work there. I would like to figure out the alternative that will work on the MySQL database. Kindly help me out. The query is as follows.

SELECT A_id, B_id, Created_at
FROM
(
   SELECT a.id as A_id, b.id as B_id, b.Created_at,
          ROW_NUMBER() OVER (PARTITION BY a.id ORDER BY b.Created_at DESC) AS rn
   FROM beta b 
   JOIN alpha a ON b.a_id = a.id 
) q
WHERE rn = 1
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
Mariwa
  • 45
  • 5

1 Answers1

1

You may use a join to subquery which finds the latest record for each id:

SELECT a.id AS A_id, b.id AS B_id, b.Created_at
FROM alpha a
INNER JOIN beta b
    ON a.id = b.a_id
INNER JOIN
(
    SELECT a.id AS max_id, MAX(b.Created_at) AS max_created_at
    FROM alpha a
    INNER JOIN beta b ON a.id = b.a_id
    GROUP BY a.id
) t
    ON t.max_id = a.id AND t.max_created_at = b.Created_at;

The idea here is that the additional join to the subquery above aliased as t will only retain the record, for each a.id, having the latest Created_at value from the B table. This has the same effect as your current approach using ROW_NUMBER, without actually needing to use analytic functions.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360