MySql - 检索每个子组中的最后一条记录

时间:2013-02-08 12:37:21

标签: mysql sql group-by greatest-n-per-group

1.购买表

Id   user     pur_type
----------------------
1    408       5-12
2    408       5-12
3    222       1-11
4    222       5-12
5    408       1-11
6    408       1-11

2。货物表

Id   parts    days
-----------------
1    1-11      50
2    5-12      40

我实现了这样的查询

SELECT p1.id, p1.user, p1.pur_type, g.parts, g.days
FROM purchase p1
INNER JOIN goods g ON p1.pur_type = g.parts
LEFT JOIN goods p2 ON ( p1.pur_type= p2.pur_type
AND p1.id < p2.id )
WHERE p2.id IS NULL

结果只是每个pur_type的最后一条记录

Id   user   pur_type  parts   days
---------------------------------
4    222     5-12     5-12    40
6    408     1-11     1-11    50

如何从一个特定用户的每个purchase的{​​{1}}表中获取最后一条记录?

例如对于用户408需要结果:

pur_type

结果说明:
用户408的最后记录fot Id user parts days ------------------------- 2 408 5-12 40 6 408 1-11 50 5-12是part = 2
用户408的id 1-11的最后记录是part = 6

2 个答案:

答案 0 :(得分:0)

SELECT  a.*, c.* -- select columns youw ant
FROM    Purchase a
        INNER JOIN
        (
            SELECT user, MAX(ID) max_ID
            FROM    Purchase
            GROUP   BY user, pur_type
        ) b ON  a.user = b.user AND
                a.ID = b.max_ID
        INNER JOIN goods c
            ON a.pur_type = c.parts
WHERE   a.USER = 408

为了获得更好的效果,请在表parts上的goods列上添加一个INDEX以及pur_type

答案 1 :(得分:0)

对现有查询的简单修改:

SELECT p1.id, p1.user, p1.pur_type, g.parts, g.days
FROM purchase p1
INNER JOIN goods g ON p1.pur_type = g.parts
LEFT JOIN purchase p2 
       ON ( p1.pur_type= p2.pur_type AND p1.id < p2.id AND p1.user=p2.user)
WHERE p2.id IS NULL and p1.user = 408