[英]SQL alternative for fetching latest record of each item in a table using partition
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.我一直在查询数据库以使用适用于 MariaDB 10.4* 版的 PARTITION 和 ROW_COUNT() 来共同获取最新记录或每个项目,但我想在 MySQL 5.7* 版数据库上查询相同的内容,但它在那里不起作用。 I would like to figure out the alternative that will work on the MySQL database.
我想找出适用于 MySQL 数据库的替代方案。 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
You may use a join to subquery which finds the latest record for each id
:您可以使用连接到子查询来查找每个
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.这里的想法是,上面别名为
t
的子查询的附加连接将只保留记录,对于每个a.id
,具有来自 B 表的最新Created_at
值。 This has the same effect as your current approach using ROW_NUMBER
, without actually needing to use analytic functions.这与您当前使用
ROW_NUMBER
方法具有相同的效果,而实际上不需要使用分析函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.