简体   繁体   English

MySql的:选择每个组的最大值与相应的ID值

[英]MySql: Select max value of per group with corresponding id of value

From my table, I want to select max likes in each user_id group with corresponding cat_id. 从我的表中,我想在每个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 http://sqlfiddle.com/#!9/51869/1

The expected result : 预期结果

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

But in the editor result is different. 但是在编辑器中结果是不同的。 What am I doing wrong? 我究竟做错了什么?

SQL Fiddle Demo SQL小提琴演示

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

OUTPUT 输出值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM