MySql:选择具有相应id值的每组的最大值

时间:2016-02-25 15:45:01

标签: mysql

从我的表中,我想在每个user_id组中选择最大喜欢与相应的cat_id。

DROP TABLE IF EXISTS likes;
CREATE TABLE likes
(
  user_id int,
  likes int,
  cat_id int
);

insert into likes(user_id, likes, cat_id) values
(2, 5, 56), 
(2,6,61), 
(2,7,70), 
(3,10,56), 
(3,11,61),
(3,9,70),
(4,14,56),
(4,15,61),
(4,16,70);

http://sqlfiddle.com/#!9/51869/1

预期结果

  user_id   max(likes)  cat_id
       2          7        70
       3         11        61
       4         16        70

但在编辑结果上有所不同。我做错了什么?

1 个答案:

答案 0 :(得分:0)

<强> SQL Fiddle Demo

SELECT  likes.user_id, likes.likes, cat_id 
FROM likes
JOIN (
       Select user_id, max(likes) mlike
       from likes 
       group by user_id) T
    on likes.user_id = T.user_id
   and likes.likes = T.mlike

<强>输出

| user_id | likes | cat_id |
|---------|-------|--------|
|       2 |     7 |     70 |
|       3 |    11 |     61 |
|       4 |    16 |     70 |