从我的表中,我想在每个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
但在编辑结果上有所不同。我做错了什么?
答案 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 |