0

1.Purchase table

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. goods table

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

I implemented such query

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

The result is only last record for each pur_type

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

How to get last record from purchase table of each pur_type for one specific user?

for example for user 408 need result:

Id   user     parts   days
-------------------------
2    408       5-12    40
6    408       1-11    50

Result explanation:
last record fot part 5-12 for user 408 is id=2
last record for part 1-11 for user 408 is id=6

4

2 回答 2

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以及pur_type

于 2013-02-08T12:39:56.797 回答
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
于 2013-02-08T12:52:29.557 回答