Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

request a sql query

Tags:

mysql

I Have a Table For example posts With this structure and Data :

ID | CatID | SubCatID | Title
-----------------------------
1 | 84 | 85 | Test 1
2 | 84 | 86 | Test 2
3 | 84 | 87 | Test 3
4 | 84 | 85 | Test 4
5 | 84 | 85 | Test 5
6 | 84 | 86 | Test 6

I want 1 query that return rows that group by SubCatID and return rows that have a MaxID From each SubCat

It means I want to return this list:

ID | CatID | SubCatID | Title
--------------------------------
5 | 84 | 85 | Test 5
6 | 84 | 86 | Test 6
3 | 84 | 87 | Test 3
like image 398
DJafari Avatar asked Mar 19 '26 13:03

DJafari


2 Answers

SELECT t.ID, t,CatID, t.SubCatID, t.Title
    FROM YourTable t
        INNER JOIN (SELECT MAX(ID) AS MaxID, CatId, SubCatID
                        FROM YourTable
                        GROUP BY CatId, SubCatID
                   ) q
            ON t.CatId = q.CatId
                AND t.SubCatID = q.SubCatID
                AND t.ID = q.MaxID
like image 133
Joe Stefanelli Avatar answered Mar 22 '26 12:03

Joe Stefanelli


select t1.* from table as t1
inner join (
select max(id) as greater from table group by subcatid) as t2
on t1.id = t2.greater
like image 34
Nicola Cossu Avatar answered Mar 22 '26 12:03

Nicola Cossu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!