加入并过滤两组相同的表

时间:2013-11-25 18:56:25

标签: mysql sql

我想这是一个简单而愚蠢的问题,但考虑到这个mysql“购买”表(其中p_id是自动递增的):

+---------+-------------+---------------+---------+
|   p_id  |    item_id  |  user_id      | count   | ... 
+---------+-------------+---------------+---------+
|       1 | 4           |             1 |       22|
|       2 | 4           |             2 |        1|
|       3 | 1           |             1 |        1|
|       4 | 0           |             3 |        1|
|       5 | 3           |             1 |      182|
|       6 | 0           |             4 |        1|
|       7 | 3           |             2 |        7|
|       8 | 3           |             2 |       14|
+---------+-------------+---------------+---------+

获取ids为1和2的用户购买了相同商品的行,并且只检索了他们上次购买这些商品的行的适当方式(查询)是什么? 结果应该是这样的:

+---------+-------------+---------------+---------+
|    p_id |    item_id  |  user_id      | count   | ... 
+---------+-------------+---------------+---------+
|       1 | 4           |             1 |       22|
|       2 | 4           |             2 |        1|
|       5 | 3           |             1 |      182|
|       8 | 3           |             2 |       14|
+---------+-------------+---------------+---------+

非常感谢,抱歉我的英语不好!

1 个答案:

答案 0 :(得分:1)

试试这个

SELECT p.p_id,p.item_id,p.user_id,p.`count`
FROM purchase p,
   (SELECT MAX(P1.p_id)as p_id,item_id,user_id
    FROM purchase P1
    WHERE EXISTS (SELECT 1 FROM purchase P2
                  WHERE P2.item_id = P1.item_id
                  AND P2.user_id <> P1.user_id
                  AND P2.user_id IN (1,2))
    AND P1.user_id IN (1,2)
    GROUP BY item_id,user_id)as result
WHERE result.p_id = p.p_id
ORDER BY p.p_id;

结果

1|4|1|22
2|4|2|1
5|3|1|182
8|3|2|14