Skip to content
Advertisement

How to get the last row in the table using group by with Order by DESC?

I have two tables, table one name (tbl_brands) with these columns:

enter image description here

and second table name (tbl_loader_attachment) with these columns:

enter image description here

I used this MySQL code below to sort by 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

When I execute my code select the first row appear (test1) I want to select the last row get (test4)

Advertisement

Answer

One approach uses a GROUP BY query:

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;

If you are using MySQL 8+ (or should a future reader of this question be using MySQL 8+), then another option here is to use 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;
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement