请求一个SQL查询

时间:2011-08-08 21:32:27

标签: mysql

我有一个表例如posts这个结构和数据:

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

我希望1个查询返回按SubCatID分组的行,并返回具有每个SubCat的MaxID的行

这意味着我想要返回此列表:

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

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