mySQL - GROUP BY但获取最新行

时间:2011-12-13 22:55:09

标签: mysql

我有一张预算表:

user_id     product_id   budget      created 
-----------------------------------------------------------------
   1             1        300      2011-12-01
   2             1        400      2011-12-01
   1             1        500      2011-12-03
   2             2        400      2011-12-04

我还有一个manager_user表,与用户一起加入经理

 user_id    manager_id    product_id
 ------------------------------------
    1           5             1
    1           9             2
    2           5             1
    2           5             2
    3           5             1

我想做的是抓住分配给经理#5的每个用户,并获得他们的'预算'......但只有最新的用户。

现在我的陈述如下:

SELECT * FROM manager_user mu 
LEFT JOIN budget b 
ON b.user_id = mu.user_id AND b.product_id = mu.product_id 
WHERE mu.manager_id = 5
GROUP BY mu.user_id, mu.product_id
ORDER BY b.created DESC;

问题是它没有提取最近的预算。有什么建议?谢谢!

2 个答案:

答案 0 :(得分:0)

要完成任务,您可以执行以下操作:

select b1.user_id, 
       b1.budget
from budget b1 inner join (
  select b.user_id, 
         b.product_id, 
         max(created) lastdate
  from budget b
  group by b.user_id, b.product_id ) q
on b1.user_id=q.user_id and 
   b1.product_id=q.product_id and 
   b1.created=q.lastdate
where b1.user_id in 
  (select user_id from manager_user where manager_id = 5);

我假设你的(user_id,product_id,created)组合是唯一的。

答案 1 :(得分:0)

对于它的价值,这里的代码返回了我想要的内容:

SELECT DISTINCT(b1.id),mu.user_id,mu.product_id,b1.budget,b1.created
FROM budget b1
INNER JOIN (
   SELECT b.user_id, b.product_id, MAX(created) lastdate
   FROM budget b
   GROUP BY b.user_id, b.product_id) q 
ON b1.user_id=q.user_id AND 
  b1.product_id=q.product_id AND 
  b1.created=q.lastdate
RIGHT JOIN manager_user mu 
    ON mu.user_id = b1.user_id AND 
    mu.product_id = b1.product_id
WHERE mu.manager_id = 5;

感谢Andrea的帮助!