如何使用groupby with order by desc获取表中的最后一行?

x33g5p2x  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(306)

我有两个表,表1名称(tblèU品牌)有以下列:

第二个表名(tbl\u loader\u attachment)包含以下列:

我使用下面的mysql代码按desc排序:

SELECT tbl_loader_attachment.*, tbl_brands.*  FROM tbl_loader_attachment
INNER JOIN tbl_brands ON(tbl_brands.b_id=tbl_loader_attachment.b_id)
GROUP BY tbl_loader_attachment.b_id ORDER BY tbl_loader_attachment.la_id DESC

当我执行代码时,选择出现的第一行(test1),我想选择最后一行get(test4)

nhn9ugyo

nhn9ugyo1#

一种方法使用 GROUP BY 查询:

SELECT tla1.*, tb.*
FROM tbl_brands tb
INNER JOIN tbl_loader_attachment tla1
    ON tb.b_id = tla1.b_id
INNER JOIN
(
    SELECT b_id, MAX(la_id) AS max_la_id
    FROM tbl_loader_attachment
    GROUP BY b_id
) tla2
    ON tla1.b_id = tla2.b_id AND
       tla1.la_id = tla2.max_la_id;

如果您使用的是mysql 8+(或者这个问题的未来读者应该使用mysql 8+),那么这里的另一个选项是 ROW_NUMBER :

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY b_id ORDER BY la_id DESC) rn
    FROM tbl_loader_attachment
)

SELECT tla.*, tb.*
FROM tbl_brands tb
INNER JOIN cte tla ON tb.b_id = tla.b_id
WHERE tla.rn = 1;

相关问题